Javascript 如何在子组件中调用父函数
我检查了很多示例,但发现大多数示例都在子组件中触发了事件。Javascript 如何在子组件中调用父函数,javascript,reactjs,Javascript,Reactjs,我检查了很多示例,但发现大多数示例都在子组件中触发了事件。 有人能建议我如何通过父组件上的单击事件在子组件中调用父组件的函数吗?谢谢 父组件(app.js): 如果要在子组件中调用它,则需要一个事件来触发它,或者可能需要一个条件。因此,例如,在您的表单.js中,我们将从您的子组件中单击一个按钮来触发它 render() { const { text } = this.state; return ( <TextField value={text
有人能建议我如何通过父组件上的单击事件在子组件中调用父组件的函数吗?谢谢 父组件(
app.js
):
如果要在子组件中调用它,则需要一个事件来触发它,或者可能需要一个条件。因此,例如,在您的
表单.js
中,我们将从您的子组件中单击一个按钮来触发它
render() {
const { text } = this.state;
return (
<TextField
value={text}
color="secondary"
/>
<Button onClick={this.props.Click} />
)
}
}
render(){
const{text}=this.state;
返回(
)
}
}
也许,在您的子组件中使用按钮并不是一个很好的选择,因为您已经在父组件中有了一个按钮来调用Click函数,我在子组件中创建的这个按钮只是一个例子,您可以使用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>
)
)
//创建引用
构造函数(){
超级();
this.myFormRef=React.createRef()
}
//单击该按钮的处理程序
handleClick=(e,id,text)=>{
//这里有一个子实例,它允许您访问它的函数
this.myFormRef.SomeChildMethods是属于thechildClass()的
}
render(){
//注意这里我们通过…ref={this.myFormRef}在表单上使用ref
返回(
this.handleClick(e,todo.id,todo.text)}>
编辑图标
)
)
我想指出的是,你为什么要这样做似乎没有多大意义。您可能应该重新思考您的架构。还有,按下按钮应该做什么?提交表格 我不明白,你的函数在父函数中,你的按钮在父函数中,为什么你要在子函数中调用它?通常人们面临的类似问题是,当按钮在子组件中,函数在父组件中时,在这种情况下,至少在设计方面是有意义的,因为我的表单在子组件中。我认为这不是一个好的设计,在子组件中有按钮是好的。我知道这样做是可行的,但我在子组件中没有任何按钮,我只想通过父组件上的单击事件将文本值传递给子组件。@JasonWilliam在您的
表单.js
,
中尝试此操作,并从父组件的按钮触发更改
render() {
const { text } = this.state;
return (
<TextField
value={text}
color="secondary"
/>
<Button onClick={this.props.Click} />
)
}
}
// 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>
)
)