我有一个表单,用于添加食谱,其中有成分按钮。配方可以有很多成分。单击该按钮时,添加成分的输入字段应显示在成分按钮下方。我试图做的是什么?
import Input from './Input.jsx';
export default class Sell extends Component {
constructor()
{
super();
this.state = {
inputValues : {}
}
this.onHandleSubmit =this.onHandleSubmit.bind(this);
}
onChange( name, { target : { value } })
{
const inputValues = this.state.inputValues;
inputValues[name] = value;
this.setState({ inputValues })
}
onHandleSubmit()
{
console.log('clicked');
const name = `ingrediant-${Object.keys(this.state.inputValues).length}`;
let inputbox = <Input name={ name }
onChange={ this.onChange.bind(this, name )} />
}
onSubmit(event){
event.preventDefault();
}
render() {
return (
<div className="row">
<h2 className="flow-text text-center">Add Recipe</h2>
<form onSubmit={this.onSubmit} className="col offset-s4 s4">
<div className="row">
<div className="input-field col s12">
<input ref="name" id="name" type="text" className="validate flow-text" />
<label htmlFor="name">Name of Recipe</label>
</div>
</div>
<div className="input-field col s12">
<a onClick={this.onHandleSubmit} className="waves-effect waves-light btn btn-block"><i className="material-icons right">add</i>Ingredients</a>
</div>
</div>
{this.state.inputValues}
<div className="row">
<button className="waves-effect waves-light btn btn-block">Submit</button>
</div>
</form>
</div>
);
}
}
如何在点击按钮时为配料创建新的动态(新创建的输入框的不同参考)输入字段?
答案 0 :(得分:1)
在你的情况下,我会将输入作为单独的组件,如
class Input extends Component
{
render()
{
const { name, onChange } = this.props;
return(<div className="row">
<div className="input-field col s12">
<input id={name}
type="text"
className="validate flow-text"
onChange={ this.props.onChange } />
<label htmlFor={name}>Name of Recipe</label>
</div>
</div>)
}
}
并且从Sell
组件传递onChange回调,Sell
组件将保持输入的值,并且当您想要将值发送到服务器时,您将其置于状态。类似的东西:
class Sell extends Component
{
constructor()
{
super();
this.state = {
inputValues = {},
inputs : []
}
}
onChange( name, { target : { value } })
{
const inputValues = this.state.inputValues;
inputValues[name] = value;
this.setState({ inputValues })
}
onHandleSubmit()
{
const name = `incrediant-${this.state.inputs.length}`;
let inputbox = <Input name={ name }
key={this.state.inputs.length}
onChange={ this.onChange.bind(this, name )} />
const inputs = this.state.inputs;
inputs.push( inputbox );
this.setState( { inputs } );
}
...
....
render()
{
...
...
{
this.state.inputs.map( i => i );
}
}
}
在这种情况下,您不必保留refs