首页 > 解决方案 > 在第二个函数中使用 setter 方法反应原生钩子状态变化

问题描述

我有 2 个函数,function1() 和 function2()

   function2(){
    return(
<TextInput/>
)
}

export default function1(){
const [name,setName]=useState('')
return(
<View>
{function2}
</View>

}

我在第二个函数中有一些文本输入,当用户输入某些内容时,我需要更改状态(在第一个函数中)。 如何处理这种情况?

标签: react-nativereact-hooks

解决方案


将处理函数作为 props 传递并在 function2 中调用它。

 function2(props){
    //wherever you get the input call
    props.handleTextInput(inputString)
    return(
        <TextInput/>
    )
}

export default function1(){
    const [name,setName]=useState('');

    const handleTextInput = (name) => {
        setName(name);
    }

    return(
        <View>
            <function2 handleTextInput = {this.handleTextInput} />
        </View>
    );
}

推荐阅读