[英]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. 但是问题是当我在一个组件中一起拥有2个输入字段并将该组件传递给父组件并获取值时。 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 我更改了代码,可以先在子级中创建函数以获取目标值并传递给props函数
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 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. 因此,基本上,您需要告诉
handlePriceMinMax
您要更新什么值。
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);
};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.