javascript 在reactjs中从父级调用子函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/52125409/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
call child function from parent in reactjs
提问by Ashh
My parent component
我的父组件
import EditReview from './partials/editReview'
class VenueDetails extends Component {
constructor(props) {
super(props)
this.child = React.createRef();
}
render() {
return (
<div className="place-review-text">
<EditReview {...this.props}/>
</div>
)
}
}
My child component
我的子组件
class EditReview extends Component {
onEditClick(review, editIndex) {
console.log('ppp')
}
render() {
const { handleSubmit, user, pristine, index, commentCrossClick } = this.props
return (
<div>
<Field
name="content"
component={renderTextArea}
className="form-control"
label="Write your review..."
rows={2}
/>
</div>
)
}
}
export default EditReview
I need to call onEditClickfrom the parent component. I tried thisbut doesn't work.
我需要onEditClick从父组件调用。我试过这个,但不起作用。
Kindly help me
请帮助我
Edit
编辑
After upgrade I am getting this
升级后我得到这个
Error in ./~/react-dom/lib/ReactServerRendering.js
Module not found: 'react/lib/React' in /home/user/ashish/LTC/lovethesecities-frontend/node_modules/react-dom/lib
After resolving all the errors call child function from parent in react 16
解决所有错误后,在 react 16 中从父级调用子函数
回答by Shannon Johnstone
React docs have a example of this using refs
React 文档有一个使用 refs 的例子
https://reactjs.org/docs/refs-and-the-dom.html
https://reactjs.org/docs/refs-and-the-dom.html
I'm also wondering the use case of wanting to do this, maybe some context could help with an answer?
我也想知道想要这样做的用例,也许某些上下文可以帮助回答?
回答by aravind_reddy
Try doing it like this:
尝试这样做:
import EditReview from './partials/editReview'
class VenueDetails extends Component {
render() {
return (
<div className="place-review-text">
<EditReview ref={Ref => this.child=Ref } {...this.props} />
</div>
)
}
}
and call the function in parent component as this.child.onEditClick(param1,param2)
并将父组件中的函数调用为 this.child.onEditClick(param1,param2)
EDIT1:
编辑1:
if you have to do it with react 15.x itself what you can do it is create the function in parent and pass it as a prop to child
如果您必须使用 react 15.x 本身来做,您可以做的是在父级中创建函数并将其作为道具传递给子级

