gpt4 book ai didi

javascript - Reactjs - 如何将值从子组件传递到祖父组件?

转载 作者:行者123 更新时间:2023-12-03 13:21:25 26 4
gpt4 key购买 nike

下面是在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;

ma​​in.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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com