我是个新手,正在为如何将数据从一个组件传输到另一个组件而苦苦挣扎。
我参考了一些教程和博客,但事情对我来说都不起作用。
我有两个子组件Body-content.jsx和Profile.jsx以及一个父组件parent.jsx
我想从Body-content.jsx向Profile.jsx传输一些数据。
这是我的代码
Body-content.jsx
class BodyContent extends React.Component {
componentDidMount() {
this.getUserList()
}
getUserList(){
fetch('https://jsonplaceholder.typicode.com/users')
.then(result => {
return result.json();
}).then(data =>{
this.setState({
users : data
})
})
}
render() {
const user = this.state.users.map((userData, i) => (
<CardBody>
...some code here
<Button color='primary' onClick={e => this.viewProfile(userData)}>View Profile</Button>
</CardBody>
</Card>
));
return (
<>
<div>{user}</div>
</>
)
}
viewProfile = function (data) {
}
}
export default BodyContent;profile.jsx
class Profile extends React.Component {
componentDidMount() {
}
render() {
return (
<>
<TopNav />
<main className="profile-page" ref="main">
<section>
//code goes here
</section>
</main>
</>
);
}
}
export default Profile;发布于 2019-11-18 17:47:10
将您的数据存储在父组件中,并将其作为道具发送给子组件。如果您必须在其中一个组件中更改它,则发送(也作为prop)函数,该函数将更改父组件中的数据。
代码示例:
class Parent extends React.Component {
constructor(props) {
super(props);
this.state = {someData: ''};
}
changeData(newData) {
this.setState({
someData: newData
});
}
render() {
return (
<>
<Child1 setData={this.changeData} data={this.state.someData} />
<Child2 setData={this.changeData} data={this.state.someData} />
</>
)
}
}它们都可以使用this.props.setData('newData')更改父组件中的数据
发布于 2019-11-18 17:46:38
如果您希望在子组件之间共享状态,那么您可能需要在父组件的状态中移动该属性,您可以在两个子组件之间共享该属性。
发布于 2019-11-18 17:47:25
您可以将状态提升到父零部件:
class Parent extends Component {
state = {
users
};
handleUsersChange = users => this.setState({ users });
render() {
const { users } = this.state;
return (
<React.Fragment>
<Body-content onUsersChange={ this.handleUsersChange } />
<Profile users={ users } />
</React.Fragment>
);
}
}
...
class BodyContent extends React.Component {
getUserList(){
fetch('https://jsonplaceholder.typicode.com/users')
.then(result => {
return result.json();
}).then(data =>{
this.props.handleUsersChange(data);
})
}
}https://stackoverflow.com/questions/58911627
复制相似问题