首页 > 解决方案 > 与 TouchableWithoutFeedback 一起使用时,React Children 仅期望收到一个 React Child

问题描述

在我的应用程序中,我有一个文本输入,每当用户单击屏幕上的任意位置或关闭键盘时,我想隐藏键盘并失去焦点。

我为此创建了这个函数:

interface DismissKeyBoardProps {
  children?: ReactNode
} 

const DismissKeyboard: React.FC<DismissKeyBoardProps> = ({ children }) => (
  <TouchableWithoutFeedback 
  onPress={() => Keyboard.dismiss()}> {children}
  </TouchableWithoutFeedback>
);

我像这样使用上述方法:

const App: React.FC = () => {

  return (
    <>
      <StatusBar barStyle="dark-content" />
      <SafeAreaView>
        <Text> Test </Text>
        <DismissKeyboard>
          <TextInput placeHolder= {"place holder"}/>
        </DismissKeyboard>
      </SafeAreaView>
    </>
  );
}; 

但是,当我尝试运行它时,出现错误: React.children.only expected to receive a single React element child.

我不明白为什么我会收到这个错误,什么时候DismissKeyBooard确实只有一个孩子 - TextInput

编辑: 我尝试了这样的建议解决方案,但我不断收到同样的错误。

  return (
    <View>
      <SafeAreaView>
        <>
          <DismissKeyboard>
            <TextInput style={{height: 40, borderColor: 'gray', borderWidth: 1}} placeHolder={"hint"}/>
          </DismissKeyboard>
        </>
      </SafeAreaView>
    </View>
  );

标签: reactjsreact-nativetouchablewithoutfeedback

解决方案


试着用 包裹你的孩子<View>,我想它会对你有所帮助。

const DismissKeyboard: React.FC<DismissKeyBoardProps> = ({ children }) => (
  <TouchableWithoutFeedback 
  onPress={() => Keyboard.dismiss()}> 
   <View>
    {children}
   </View>
  </TouchableWithoutFeedback>
);

推荐阅读