将react文本字段输入值作为参数传递给方法
Passing react text field input values as parameters to a method
我有下面的输入字段,我需要获取输入的输入并将其传递给下面所示按钮的onClick事件。
<input type="text" style={textFieldStyle} name="topicBox" placeholder="Enter topic here..."/>
<input type="text" style = {textFieldStyle} name="payloadBox" placeholder="Enter payload here..."/>
<button value="Send" style={ buttonStyle } onClick={this.publish.bind(this,<value of input field 1>,<value of input field2>)}>Publish</button><span/>
我有一个名为publish的方法,它接受两个字符串参数。在这些字符串的位置,我需要传递输入字段中输入的值。如何在不将值存储在状态中的情况下实现这一点?我不想将输入字段值存储在状态变量中。
我如何在不存储状态值的情况下实现这一点?
我认为在这种情况下最好使用状态
class App extends React.Component {
constructor() {
super();
this.state = {
topicBox: null,
payloadBox: null
};
this.publish = this.publish.bind(this);
this.handleChange = this.handleChange.bind(this);
}
handleChange({ target }) {
this.setState({
[target.name]: target.value
});
}
publish() {
console.log( this.state.topicBox, this.state.payloadBox );
}
render() {
return <div>
<input
type="text"
name="topicBox"
placeholder="Enter topic here..."
value={ this.state.topicBox }
onChange={ this.handleChange }
/>
<input
type="text"
name="payloadBox"
placeholder="Enter payload here..."
value={ this.state.payloadBox }
onChange={ this.handleChange }
/>
<button value="Send" onClick={ this.publish }>Publish</button>
</div>
}
}
ReactDOM.render(<App />, document.getElementById('container'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container"></div>
您可以为每个文本字段添加ref,并从中读取值,如:
class App extends React.Component {
constructor() {
super();
this.publish = this.publish.bind(this);
}
publish(topicBox, payloadBox) {
alert(this.refs.topic.value);
alert(this.refs.payload.value);
}
render() {
return <div>
<input
ref="topic"
type="text"
name="topicBox"
placeholder="Enter topic here..."/>
<input
ref="payload"
type="text"
name="payloadBox"
placeholder="Enter payload here..."/>
<button
value="Send"
onClick={this.publish}>
Publish
</button>
</div>
}
}
ReactDOM.render(<App />, document.getElementById('container'));
工作小提琴https://jsfiddle.net/hjx3ug8a/15/
感谢Alexander T的添加!
相关文章:
- 在嵌套递归指令中将参数传递给父控制器方法
- 将参数传递到外部 JS 脚本的最佳方法
- 将参数传递给回调函数而不更改方法(Siesta Testing命名空间)
- 如何将GWT方法作为参数传递到Javascript函数中
- 有没有一种方法可以将多个参数传递给主干js中的事件函数
- 将返回值作为主干视图方法之间的参数传递
- 传递和接收 $(this) 作为参数的方法
- Jasmine jQuery 测试,用于检查是否已将正确的参数传递给方法
- 在对象上调用方法或将对象作为函数参数传递的差异
- 正确的方法:始终将所有变量作为函数参数传递
- 将参数传递到 Javascript 方法中
- 如何将函数中的 JQuery 对象作为该对象的方法调用的参数传递
- 将参数传递给从另一个类调用方法的一个类上的便利方法
- 从JavaScript调用后端方法和参数传递
- 在返回作为字符串参数传递的值时使用eval()的正确方法
- 将对象作为参数传递给手把模板中的onclick方法
- 在javascript中将方法作为参数传递的惯用方法
- 在JavaScript中将方法作为参数传递
- 将 jquery 方法作为参数传递到函数中
- 如何将参数作为方法传递