gpt4 book ai didi

javascript - 将 react 文本字段输入值作为参数传递给方法

转载 作者:可可西里 更新时间:2023-11-01 02:57:53 24 4
gpt4 key购买 nike

我有以下输入字段,我需要获取输入的内容并将其传递给如下所示按钮的 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 的方法,它接受两个字符串参数。代替那些字符串,我需要传递在输入字段中输入的值。如果不将值存储在状态中,我如何才能实现这一目标?我不想将输入字段值存储在状态变量中。任何帮助将不胜感激。

最佳答案

How can I achieve this without storing the values in states?

我认为在这种情况下更好地使用状态

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>

关于javascript - 将 react 文本字段输入值作为参数传递给方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39723391/

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