【问题标题】:Getting Child Component Prop from the Parent Component从父组件获取子组件 Prop
【发布时间】:2020-05-15 08:42:19
【问题描述】:
【问题讨论】:
标签:
javascript
react-native
【解决方案1】:
您可以使用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.onClick()而不是props.onClick(),在this.onClick中,您可以使用this.textInput访问子组件。current访问子组件。 p>
【解决方案2】:
您应该根据文档使用onClick 代替onPress 来获得点击项:
onClick={props.onClick} // <-- will call parent component's onClick
// OR
onClick={(item) => props.onClick(item)} // <-- will call parent component's onClick
要检查控制台,请尝试以下代码:
onClick={(item) => { console.log(item); }}