gpt4 book ai didi

javascript - React中组件之间的数据传输

转载 作者:行者123 更新时间:2023-12-02 22:30:41 25 4
gpt4 key购买 nike

我是新手,不知道如何将数据从一个组件传输到另一个组件。

我引用了一些教程和博客,但这些对我不起作用。

我有两个子组件,Body-content.jsxProfile.jsx 以及 1 个父组件 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;

最佳答案

将数据存储在父组件中并将其作为 Prop 发送给子组件。如果您必须在其中之一中更改它,则发送(也作为 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') 更改父组件中的数据

关于javascript - React中组件之间的数据传输,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58911627/

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