我检查了很多示例,但发现大多数示例都在子组件中触发了事件。
有人可以建议我如何使用父组件上的单击事件调用子组件的父组件功能吗?谢谢。
父组件(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 in child component 只是为了举例
关于javascript - 如何在子组件中调用父函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51393272/