React JS显示提交后的数据


React JS display the data after submitting

下面是我的react代码,它接受json格式的数据并打印

          var DataInTableFormat = React.createClass({
                getInitialState: function() {
                    return {
                      phpData: [] //initial value 
                    };//getInitialState
                },//DataInTableFormat 
                componentDidMount: function() {
                    $.get(this.props.source, function(result) { //storing the JSON data in result
                      var collection = JSON.parse(result);  //coverting JSON data to Javascript object
                      console.log(collection);
                      if (this.isMounted()) {//checking for component mount
                        this.setState({
                          phpData: collection
                       });
                      }
                    }.bind(this));
                },
                   render:function()
                    {
                      DBdata = this.state.phpData || [];
                        return (
                        <form>
                        <div>Select ID :
                          <select>
                          {DBdata.map(function(d){
                            return(
                                    <option value={d.id}>{d.id}</option>//prints the all id from the jsondata.php
                                   )}
                          )}
                          </select>
                        <button name="submit">submit</button>
                       </div> 
                       </form>
                )}
          });
          React.render(
            <DataInTableFormat source="http://localhost/PHP-React-Demo/jsondata.php" />,
              document.getElementById('Table-data')
            );

当我选择ID时,我只想在点击提交后以表格格式打印所有详细信息。

您需要执行以下操作:

  1. <select>元素上定义一个onChange处理程序。

    <select onChange={this.handleChange}>
    
  2. 将事件处理程序添加到组件定义中,并使用它来更改组件实例的状态。

    handleChange: function (event) {
        this.setState({
            currentId: event.target.value
        });
    }
    
  3. render()方法中使用该状态。

    render: function () {
        var currentId = this.state.currentId;
        var phpData = this.state.phpData || [];
        var selected = phpData.filter(function (item) {
            return item.id === currentId;
        });
        if (selected.length > 0) {
            // return stuff relating to selected[0]
        }