React.js-如何将值从子组件传递到祖父母组件? [英] Reactjs - How to pass values from child component to grand-parent component?
本文介绍了React.js-如何将值从子组件传递到祖父母组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
下面是在reactjs中将值从子组件传递到父组件的正确示例.
Below is correct example for passing the values from child component to parent component in reactjs.
App.jsx
import React from 'react';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
data: 'Initial data...'
}
this.updateState = this.updateState.bind(this);
};
updateState() {
this.setState({data: 'Data updated from the child component...'})
}
render() {
return (
<div>
<Content myDataProp = {this.state.data}
updateStateProp = {this.updateState}></Content>
</div>
);
}
}
class Content extends React.Component {
render() {
return (
<div>
<button onClick = {this.props.updateStateProp}>CLICK</button>
<h3>{this.props.myDataProp}</h3>
</div>
);
}
}
export default App;
main.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
ReactDOM.render(<App/>, document.getElementById('app'));
我需要明确有关将值从子组件传递到祖父母组件的概念.请帮我.
I need clear my concept about passing the values from child component to grand-parent component. Please, help me for this.
推荐答案
您可以通过props
将更新功能传递给大子级,只需从子组件中再次传递即可.
You can pass the update function to the grand child by props
, just pass it again from the child component.
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
data: 'Initial data...'
}
this.updateState = this.updateState.bind(this);
}
updateState(who) {
this.setState({data: `Data updated from ${who}`})
}
render() {
return (
<div>
Parent: {this.state.data}
<Child update={this.updateState}/>
</div>
)
}
}
class Child extends React.Component {
render() {
return (
<div>
Child component
<button onClick={() => this.props.update('child')}>
CLICK
</button>
<GrandChild update={this.props.update}/>
</div>
);
}
}
class GrandChild extends React.Component {
render() {
return (
<div>
Grand child component
<button onClick={() => this.props.update('grand child')}>
CLICK
</button>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('root'))
<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>
<div id="root"></div>
这篇关于React.js-如何将值从子组件传递到祖父母组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文