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
Add a ment  | 

1 Answer 1

Reset to default 4
  1. Maintain the state in the parent ponent, pass it as props to the functional ponent to show the value
  2. 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