简体   繁体   中英

Create price range fields (min and max) using reactJS

after spending a lot time I need help here.

I am creating a template. Where I can use different form fields. Everything is working. I am getting value form all fields as expected.

But problem is when I have 2 input fields together in one component and pass this component to parent component and get the value. then save this value in object.

I hope its clear enough. Thank you in advance


class Parent extends Component {
  handlePriceMinMax(event) {
    console.log(event.target.value);

    /* I cant set the right values here. 
    *  These values get overwritten with latest value. 
    *  Because I get value on keypress/onChange value */
    this.setState({
            priceRange: {
                min: event.target.value, 
                max: event.target.value
            }
        }
    );
  }
  render() {
    return (
      <Child onChange={this.handlePriceMinMax}/>
    )
  }
}

class Child extends Component {
  render() {
    return (
        <div className="form-group">
            <label>Price</label>
            <input type="number" onChange={this.props.onChange}/>
            <input type="number" onChange={this.props.onChange}/>
        </div>
    );
  }
}

export default Child;

I changed my code, you can create function in child first that get target value and pass to props function

class Child extends Component {
  submitInput(e) {
    this.props.onChange(e)
  }
  render() {
    return (
        <div className="form-group">
            <label>Price</label>
            <input type="number" onChange={(e) => this.submitInput(e)}/>
            <input type="number" onChange={(e) => this.submitInput(e)}/>
        </div>
    );
  }
}

export default Child;

https://codesandbox.io/s/zr30923nrm

I think this should work. So basically you need to tell to the handlePriceMinMax what value do you want to update.

class Parent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { priceRange: { min: 0, max: 0 } };
  }
  handlePriceMinMax = (value, event) => {
    const priceRange = this.state.priceRange;
    priceRange[value] = event.target.value;
    this.setState({ priceRange });
  };
  render() {
    return <Child onChange={this.handlePriceMinMax} />;
  }
}

class Child extends React.Component {
  render() {
    return (
      <div className="form-group">
        <label>Price</label>
        <input type="number" onChange={this.minChange} />
        <input type="number" onChange={this.maxChange} />
      </div>
    );
  }

  minChange = e => {
    this.props.onChange("min", e);
  };

  maxChange = e => {
    this.props.onChange("max", e);
  };
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM