javascript - 从父组件获取子组件 Prop
问题描述
我正在使用以下 React Native 模块: https ://github.com/shariqahmed1/react-native-animated-tree-view
我喜欢从 TreeView 中获取点击的项目。
我的尝试是这样的:
<TreeView
onPress={() => console.log(props.onClick)} //Cannot get clicked item
data={data} //Works Okay
/>
我能够成功提供源数据,但无法从树视图中获取单击的项目。
如何从父组件获取子组件值?
解决方案
你可以使用Ref/createRef给它一个唯一的引用(就像 ID 一样),然后你就可以访问它了:
class CustomTextInput extends React.Component {
constructor(props) {
super(props);
// create a ref to store the textInput DOM element
this.textInput = React.createRef();
this.focusTextInput = this.focusTextInput.bind(this);
}
focusTextInput() {
// Explicitly focus the text input using the raw DOM API
// Note: we're accessing "current" to get the DOM node
this.textInput.current.focus();
}
render() {
// tell React that we want to associate the <input> ref
// with the `textInput` that we created in the constructor
return (
<div>
<input
type="text"
ref={this.textInput} />
<input
type="button"
value="Focus the text input"
onClick={this.focusTextInput}
/>
</div>
);
}
}
在 onclick 事件处理程序中,使用this.onClickthis.onClick()
代替props.onClick()
和,您可以使用 this.textInput 访问子组件。当前访问子组件。
推荐阅读
- sql - 使用原始查询时,Doctrine 语句未正确返回数据
- android - 带有保存按钮的 SharedPreferences
- javascript - 如何在对象对象 JavaScript 中查找特定值
- javascript - 将 excel 二维数组转换为包含列名的嵌套属性对象
- python - 如何从 mxnet nd 数组中访问类标签的索引?输出必须是使用函数输入的标签名称的索引
- python - 如何比较烧瓶中的两个密码
- tensorflow - Google Colab:TPU 不支持的数据类型:double,由输出 cond_8/Merge:0 引起
- ruby - 从字符串中删除空格,然后转换为整数
- git - 有什么方法可以将本地 git-p4 存储库连接到远程 git 存储库,同时保持与 p4 仓库的连接?
- google-vision - 使用没有文件扩展名的图像将训练数据导入 CloudML