javascript - 将值作为对象提交

标签 javascript reactjs object

<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/

相关文章:

javascript - 数据表过滤器数量大于

javascript - 在react-konva中转换后,矩形无法正确重新渲染

javascript - react .js : call a function from another component

javascript - JSON对象中的递归数据

javascript .push() 每次插入相同的对象

javascript - 如何从 HTML 代码中检索 <strong> 标记后的数据?

javascript - [React-Native]如何在状态栏之外渲染 View (android和ios)?

javascript - ./src/App.js 'store' 中的错误未定义

javascript - 使用 += 运算符 undefined object 中的第一个元素

javascript - onclick 事件中的函数不起作用