【发布时间】:2021-11-02 08:48:54
【问题描述】:
我有三个组件,其中 App 是父组件(基于类)和两个子组件(基于功能)名为 User & Input时间>。我已将用户导入应用程序并将输入导入用户。我想通过 Input(there is a button -> onClick) 中的值更改名称。
更新 问题是 App.jsx 中的函数(我很确定我尝试这样做的方式是正确的)。
// App.jsx
Imported User
state = {
users : [
{id: 1, fullName: 'Amirreza Amini'},
{id: 2, fullName: 'John Smith'},
...
]
};
handleChangeName = name => {
const editedUsers = [...this.state.users];
const users = editedUsers.map(user => user.fullName = name);
this.setState({ users });
};
render() {
const { users } = this.state;
const userComponent = users.map(user => (
<User
key={user.id}
fullName={user.fullName}
edit={() => this.handleChangeName(user.fullName)}
/>
));
.
// User.jsx
Imported Input
const User = ({ fullName }) => {
return (
<section>
<h1>{ fullName }</h1>
<Input fullName={fullName} />
</section>
);
};
export default User;
.
// Input.jsx
const Input = ({ fullName }) => {
return (
<section>
{/* The value of this input must be the fullName after I clicked the button */}
<input className="user-edit-input" placeholder={fullName} />
<button className="edit-button" onClick={edit(document.querySelector('.user-edit-input').value)}>Change</button>
</section>
);
};
export default Input;
【问题讨论】:
-
您可以将输入作为道具发送到用户组件的回调。从Users,通过回调函数,再调用一个函数来设置User组件的状态
标签: javascript reactjs state