[英]How to call parent function in child component
我检查了很多示例,但发现其中大多数事件在“子组件”中触发。
有人可以建议如何通过父组件上的click事件在子级中调用子组件中的父函数吗? 谢谢。
父组件( app.js
):
Class App extends Component {
handleClick = (e, id, text) => {
e.preventDefault();
this.setState({val: text})
}
render() {
return (
<div>
<Form val={this.state.val} Click={this.handleClick.bind(this) }/>
<Button onClick={(e) => this.handleClick(e, todo.id, todo.text)}>
<Icon>edit_icon</Icon>
</Button>
</div>
)
}
}
子组件( form.js
):
this.props.Click(); //where should i call this function since my button is in parent component
Class Form extends Component{
render() {
const { text } = this.state;
return (
<TextField
value={text}
color="secondary"
/>
)
}
}
}
如果要在子组件中调用它,则需要一个事件来触发它或一个条件。 因此,例如在您的form.js
,我们将通过单击子组件的按钮来触发它
render() {
const { text } = this.state;
return (
<TextField
value={text}
color="secondary"
/>
<Button onClick={this.props.Click} />
)
}
}
也许,在子组件中使用Button并不是您的最佳选择,因为您已经有一个Button可以在父组件中调用Click函数,我在子组件中创建的Button仅作为示例
一种实现方法是使用ref调用该函数。
// create the ref
constructor() {
super();
this.myFormRef = React.createRef()
}
// click handler for the button
handleClick = (e, id, text) => {
// here you have the child instance which gives you access to its functions
this.myFormRef.someChildMethodThatIsOnTheChildClass()
}
render() {
// notice here we use the ref on the form via... ref={this.myFormRef}
return (
<Form val={this.state.val} ref={this.myFormRef} Click={this.handleClick.bind(this) }/>
<Button onClick={(e) => this.handleClick(e, todo.id, todo.text)}>
<Icon>edit_icon</Icon>
</Button>
)
)
我想指出的是,对于您为什么要这样做似乎似乎没有多大意义。 您可能应该重新考虑您的体系结构。 另外,按下按钮应该做什么? 提交表格?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.