gpt4 book ai didi

javascript - 单击按钮时添加输入字段

转载 作者:行者123 更新时间:2023-11-30 00:08:24 25 4
gpt4 key购买 nike

我有一个用于添加配方的表单,其中有配料按钮。一个食谱可以有很多成分。单击该按钮时,用于添加成分的输入字段应出现在成分按钮下方。我试图做的是?

enter image description here

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>
);
}
}

如何在单击按钮时为成分创建新的动态(新创建的输入框的不同 ref)输入字段?

最佳答案

在你的情况下,我会让输入成为一个单独的组件,比如

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

关于javascript - 单击按钮时添加输入字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37537178/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com