提交值作为对象

时间:2017-09-16 14:17:07

标签: 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>

1 个答案:

答案 0 :(得分:1)

你可以将它们包裹在这样的object中:
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>