Answer the question
In order to leave comments, you need to log in
Is it possible to change the state of an external component through props?
Recently I ran into a problem - changing the state through changes in the internal component. I know that it is possible to pass an external function inside the component, which will change via this.setState({ something: input parameter });
Let's say:
// InnerComponent
// Тут код компонента
// Внутри компонента, допустим, на input'e, меняем this.props.text через onChange
// State of App component
this.state = {
text: 'Hello world'
}
render() {
return <InnerComponent text={this.state.text} />
}
Answer the question
In order to leave comments, you need to log in
1. If you try to change this.props , you will get an exception:
2. You have the ability to mutate state , but you don't have to.
A good way to manage the state of components is through the parent:
class Example extends Component {
state = {
inputValue: '',
};
handleChange = e => {
const { name, value } = e.target;
this.setState({
[name]: value,
});
};
render() {
const { inputValue } = this.state;
return (
<Wrapper>
<input
name="inputValue"
value={inputValue}
onChange={this.handleChange}
/>
...
</Wrapper>
);
}
Purely an example, it is possible to make more beautiful.
this.state = {
text: 'Hello world'
}
handleChangeText = text => {
this.setState({ text })
}
render() {
return <InnerComponent handleChangeText={this.handleChangeText} text={this.state.text} />
}
const InnerComponent = ({ handleChangeText }) => {
return (
<div onClick={() => handleChangeText('some text')}>text</div>
);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question