我正在阅读有关Medium的教程,该教程解释了如何将数据从子组件传递到父组件(https://medium.com/@ruthmpardee/passing-data-between-react-components-103ad82ebd17)。该教程获得了5.5k点赞,这意味着很多人必须在自己的工作中使用它作为参考。但是,在复制代码1:1时,我完全无法获得相同的结果。实际上,数据根本没有从孩子传递给父母。另外,当我强制数据通过时,我遇到了无限循环。如果有人指出我错了,或者实际上毕竟是本教程,我将不胜感激。
JS摆弄我的代码: https://jsfiddle.net/lightspeed12/69z2wepo/216279/
class ToDoItem extends React.Component {
someFn = () => {
let listInfo = 'Hi mom'
this.props.callBackFromParent(listInfo);
}
render(){return <h3>Hello World</h3>}
};
class ToDoList extends React.Component {
constructor(props){
super(props)
this.state = {
listDataFromChild: null
}
}
myCallback = (dataFromChild) => {
this.setState({ listDataFromChild : dataFromChild })
}
otherFn = () => {
console.log(this.state.listDataFromChild, 'from state')
}
render(){
this.otherFn(); //calling otherFn to determine value of this.state.listDataFromChild
return (
<div>
<h2>Message from Child is:</h2>
<ToDoItem
callBackFromParent={this.myCallback}
/>
</div>
)
}
}
ReactDOM.render(
<ToDoList />,
document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
答案 0 :(得分:0)
this.someFn()
中的 ToDoItem
。
尝试:
// To-do Item.
class ToDoItem extends React.Component {
// Render.
render = () => <h3>Hello World</h3>
// Did Mount.
componentDidMount() {
this.props.callBackFromParent('Callback Received.')
}
}
请参阅以下有关functional prop
为passed
和executed
的实际示例。
// Parent.
class Parent extends React.Component {
// State.
state = {data: null}
// Callback.
callback = data => this.setState({data})
// Render.
render(){
const {data} = this.state
console.log('Data:', data)
return (
<React.Fragment>
<h2>Parent</h2>
<Child callback={this.callback}/>
Data: {data || 'null'}
</React.Fragment>
)
}
}
// Child.
const Child = props => <button onClick={() => props.callback('Callback Received.')}>Child.</button>
// Mount.
ReactDOM.render(<Parent/>,document.querySelector('#root'))
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root"></div>
答案 1 :(得分:0)
this.someFn()
,它会调用ToDoList组件的回调方法。点击按钮即可调用this.someFn()
。
class ToDoItem extends React.Component {
someFn = () => {
let listInfo = 'Hi mom'
this.props.callBackFromParent(listInfo);
}
componentDidMount() {
this.someFn()
}
render(){return <h3>Hello World</h3>}
};
来自子级的数据可以查看为
render(){
return (
<div>
<h2>Message from Child is:{this.state.listDataFromChild}</h2>
<ToDoItem
callBackFromParent={this.myCallback}
/>
</div>
)
}