【问题标题】:how can i get a value from a child component to parent screen in react native?如何在反应原生中从子组件到父屏幕获取值?
【发布时间】:2022-01-05 16:27:43
【问题描述】:

嗨,我是新来的原生反应...我的问题是,我们如何从父屏幕捕获子组件中设置的值?这是一个示例代码(父级和子级位于不同的 source_files 中).. 我如何从 ParentScreen 读取变量 count 中的值?当在子控件中点击Count++按钮时,txtFromChild变量需要更新..我们该怎么做呢?

ParentScreen.js

const ParentScreen= () => {     
    const [txtFromChild, setTextFromChild ) = useState('');         

    return (
        <View>
        <Text>{txtFromChild}</Text>
        <ChildControl />
        </View>    
    );    
};    
export default ParentScreen;

这是单独文件中的子控件

ChildControl.js
    const ChildControl= () => {     
    const [count, setCount ) = useState(0);       

    return (
        <View>
        <Button title="Count++" onPress={()=>{setCount(count+1)}}/>
        </View>    
    );    
};    
export default ChildControl;

【问题讨论】:

  • 使用回调函数
  • @assembler,怎么样?你能解释一下吗?..我已经在 onPress 事件中有一个函数..那么我们应该如何添加回调?...这也是标准方法吗?...或者还有其他方法吗?方法?
  • 在子组件的props中传递一个函数,然后从子组件内部调用。
  • 感谢@Prateek,汇编程序,

标签: reactjs react-native


【解决方案1】:

ParentScreen.js

有多种获取价值的方法。最简单的方法是从函数中获取该值。只需尝试此代码,一旦您在子视图中单击该按钮,您就会在父视图中获得该计数。

const ParentScreen = () => {
  const [txtFromChild, setTextFromChild] = useState("");

  const getCountValue = (yourvalue) => {
    console.log(yourvalue);
  };
  return (
    <View>
      <Text>{txtFromChild}</Text>
      <ChildControl getCountValue={(value) => getCountValue(value)} />
    </View>
  );
};
export default ParentScreen;

ChildControl.js

  const ChildControl = (getCountValue) => {
  const [count, setCount] = useState(0);

  const onPressButton = async () => {
    await setCount(count + 1);
    getCountValue(count);
  };
  return (
    <View>
      <Button title="Count++" onPress={() => onPressButton()} />
    </View>
  );
};
export default ChildControl;

【讨论】:

  • 好的,谢谢@Manojkanth
  • 很高兴为您提供帮助.. 干杯
猜你喜欢
  • 1970-01-01
  • 2020-02-04
  • 2017-12-23
  • 2020-10-25
  • 2020-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多