<div>
Player One <input ref="p1Name"/>
Player Two <input ref="p2Name"/>
<button onClick={() => this.submit(this.refs.p1Name.value, this.refs.p2Name.value)}>submit result</button>
</div>
此代码按预期提交。但我想将其作为对象提交。我尝试将参数包装在 {}
中,但随后它提示 this
关键字。我如何提交它以便函数将其作为对象接收?
这是我尝试过的:
<button onClick={() => this.submit({this.refs.p1Name.value, this.refs.p2Name.value})}>submit result</button>
最佳答案
您可以将它们包装在一个对象
中,如下所示:
this.submit({a: this.refs.p1Name.value, b: this.refs.p2Name.value})}
一个工作示例:
class App extends React.Component {
constructor(props) {
super(props);
this.submit = this.submit.bind(this);
}
submit(params) {
console.log(params);
}
render() {
return (
<div>
Player One <input ref="p1Name" />
Player Two <input ref="p2Name" />
<button
onClick={() =>
this.submit({a: this.refs.p1Name.value, b: this.refs.p2Name.value})}
>
submit result
</button>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<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="root"></div>
关于javascript - 将值作为对象提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46254866/