Eu tenho três componentes em que App é o componente pai (baseado em classe) e dois componentes filhos (baseado em funções) chamados User & Input . Importei usuário para aplicativo e entrada para usuário. Eu quero mudar o nome pelo valor em Input ( há um botão -> onClick ).
Atualizado O problema é a função no App.jsx (tenho quase certeza de que a maneira como tento fazer isso é verdadeira).
// 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;
Duas grandes opções a meu ver:
A primeira opção é alterar App.jsx para componente funcional e enviar a função para alterar o nome completo para User.jsx e o para Input.jsx como adereços, permitindo que o componente de entrada altere o valor por si mesmo
A segunda opção, que pode deixar seu componente App.jsx como está, mantê-lo mais seguro e permitir que o componente filho lide apenas com o que realmente precisa saber, é, da mesma forma, enviar uma função do componente App pai para que o componente Input possa acionar o envio o nome completo antigo e o novo nome completo e a função do componente pai cuidariam do resto do processo.
exemplo para função pai:
const updateFullname = (previousName, newName) => {
// Get previous object data and location in array
let originalUsersState = this.state.users;
let originalUser = originalUsersState.filter(
(user, index) => user.fullName === previousName
)
const originalUserIndex = originalUsersState.findIndex(
(user, index) => user.fullName === previousName
)
// Create new updated object and insert it to updated object array
let updatedUser = originalUser
updatedUser.fullName = newName;
let updatedUsersState = originalUsersState;
updatedUsersState[originalUserIndex] = updatedUser;
// Update the state with the new updated object array
this.setState(
{
users: updatedUsersState
}
);
}
Abriviação de uma solução para o código da pergunta com a nova função e processo propostos:
// 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 });
};
const updateFullname = (previousName, newName) => {
// Get previous object data and location in array
let originalUsersState = this.state.users;
let originalUser = originalUsersState.filter(
(user, index) => user.fullName === previousName
)
const originalUserIndex = originalUsersState.findIndex(
(user, index) => user.fullName === previousName
)
// Create new updated object and insert it to updated object array
let updatedUser = originalUser
updatedUser.fullName = newName;
let updatedUsersState = originalUsersState;
updatedUsersState[originalUserIndex] = updatedUser;
// Update the state with the new updated object array
this.setState(
{
users: updatedUsersState
}
);
}
render() {
const { users } = this.state;
const userComponent = users.map(user => (
<User
key={user.id}
fullName={user.fullName}
updateFullname={updateFullname}
edit={() => this.handleChangeName(user.fullName)}
/>
));
// User.jsx
Imported Input
const User = ({ fullName, updateFullname }) => {
return (
<section>
<h1>{ fullName }</h1>
<Input fullName={fullName} updateFullname={updateFullname} />
</section>
);
};
export default User;
// Input.jsx
const Input = ({ fullName }) => {
const [inputValue, setInputValue] = useState(undefined);
return (
<section>
<input className="user-edit-input" value={inputValue} onChange={event => setInputValue(event.target.value)} placeholder={fullName} />
<button className="edit-button" onClick={(fullname, inputValue) => updateFullname}>Change</button>
</section>
);
};
export default Input;
Este artigo é coletado da Internet.
Se houver alguma infração, entre em [email protected] Delete.
deixe-me dizer algumas palavras