admin管理员组文章数量:1389249
I would like to reflect a value inside the div
tag that you choose from the following select tag right after the value changes by onChange
when you use a React Functional Component, so you can't use setState
function. Under the prerequisite, how do you call render method (or, re-render the value inside the div) according to the value change? Any idea?
<select onChange={foo}>
<option value="1">1</option>
<option value="2">2</option>
</select>
<div>{value}</div>
I would like to reflect a value inside the div
tag that you choose from the following select tag right after the value changes by onChange
when you use a React Functional Component, so you can't use setState
function. Under the prerequisite, how do you call render method (or, re-render the value inside the div) according to the value change? Any idea?
<select onChange={foo}>
<option value="1">1</option>
<option value="2">2</option>
</select>
<div>{value}</div>
Share
Improve this question
asked Jul 30, 2018 at 5:41
diveintohackingdiveintohacking
5,2237 gold badges32 silver badges43 bronze badges
3
- 1 Handle state in a parent and pass down an onChange handler and value? – Andrew Li Commented Jul 30, 2018 at 5:43
- as far I know if you have state maintained like in redux you can manage state by dispatching actions or if you do not have redux neither you want it then pass a function from parent to child and call that function from child and in that function change your state. – Shubham Agarwal Bhewanewala Commented Jul 30, 2018 at 6:03
- I don't use Redux, but use just a local variable in the application. – diveintohacking Commented Jul 30, 2018 at 6:45
1 Answer
Reset to default 4- Maintain the state in the parent ponent, pass it as props to the functional ponent to show the value
- Pass the onChange from parent to functional child ponent as well.
Like this,
function Child({ value, onChange }) {
return (
<div>
<select onChange={onChange}>
<option value="1">1</option>
<option value="2">2</option>
</select>
<div>{value}</div>
</div>
);
}
class Parent extends Component {
constructor(props) {
super(props);
this.state = {
value: ''
};
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) {
this.setState({
value: e.target.value
});
}
render() {
return <Child value={this.state.value} onChange={this.handleChange} />;
}
}
本文标签: javascriptHow to rerender in a React Functional Component According to a onChangeStack Overflow
版权声明:本文标题:javascript - How to re-render in a React Functional Component According to a onChange? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744591036a2614490.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论