下面是在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'));
我需要明确关于将值从子组件传递到祖 parent 组件的概念。请帮助我!.
最佳答案
可以通过props
将更新函数传递给孙组件,只需在子组件中再次传递即可。
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>
关于javascript - Reactjs - 如何将值从子组件传递到祖父组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41121667/