React Js:将数据从父级传递到一个以上的子级组件

时间:2018-11-14 20:52:30

标签: javascript reactjs

我是ReactJs的新手,最初我可以使用状态对象将数据从Parent传递给child。现在,我只能从父级传递到一个子级组件,我需要将其传递给另一个子级组件,而当我使用相同的技术执行此操作时,我无法在第二个子级组件中获取数据,它表示未定义。从父母->空白->子1->显示详细信息->子2->电话。请建议

在父级中  ->我可以在孩子1中找回  ->我无法在儿童2的电话中检索

   import React, { PropTypes , Component } from 'react';
    import './blank.css';
    import {
      Panel,
      Button,
      PageHeader,
      ControlLabel,
      FormControl,
      Pagination,
      FormGroup} from 'react-bootstrap';
    import JwPagination from 'jw-react-pagination';
    import FormControlFeedback from 'react-bootstrap/lib/FormControlFeedback';
    import FormControlStatic from 'react-bootstrap/lib/FormControlStatic';
    import InputGroupAddon from 'react-bootstrap/lib/InputGroupAddon';
    import {Link, BrowserRouter as Router,Route} from 'react-router-dom'; 

    const customStyles = {
      ul: {
          backgroundColor: 'red'
      },
      li: {
          border: '1px solid green'
      },
      a: {
          color: 'blue'
      }
    };
    const title = 'Customer-LookUp';
    const spacing = {
      marginRight: "20px",
      marginbottom: "20px"
    }
    const buttonalignment = {
      marginLeft: "81px",
      marginbottom: "20px"
    }

    class displayBlank extends Component {
      constructor(props) {
        super(props);
        this.state = {
              newData: [],
              pageOfItems: [],
              respData:[],
              sort: {
                column: null,
                direction: 'desc',
              }
          };
        this.handleSubmit = this.handleSubmit.bind(this);
        this.searchFunction = this.searchFunction.bind(this);
        this.setArrow = this.setArrow.bind(this);
        this.onSort = this.onSort.bind(this);
        this.onChangePage = this.onChangePage.bind(this);
        this.handleClick = this.handleClick.bind(this);
      };

      onChangePage(pageOfItems) {
        // update local state with new page of items
        this.setState({pageOfItems});
    }
      handleSubmit(event) {
        event.preventDefault();
        const form = event.target;
        const data = new FormData(form);
        const arrayValue = [];
        var i = 0;
        console.log('Data from Form:',data);
        for (let name of data.keys()) {
          const input = form.elements[name];
          const parserName = input.dataset.parse;
          const parsedValue = data.get(name);
          console.log('name',name);
          console.log('parsedValue',parsedValue);
          if (typeof(parsedValue) == 'undefined' || parsedValue == null) {
             console.log('Not Defined or Not Null')
             arrayValue[i] = "";
             data.set(name, arrayValue[i]);
      }
      else{
        data.set(name, parsedValue);
        arrayValue[i] = parsedValue;
      }
          i=i+1;
        }
    console.log('brandname:after get',arrayValue[0]);
    console.log('LastName:after get',arrayValue[2]);
    console.log('zipcode:after get',arrayValue[8]);
    var response_data = "";
    var response_jsonObj ;
    var txt = "";
    var req = {"CustomerLookupRequest" : [{
    "Field1":arrayValue[0],
    "Field2": arrayValue[1],
    "Field3":arrayValue[2],
    "Field4":arrayValue[3],
    "Field5":arrayValue[4],
    "Field6":arrayValue[5],
    "Field7":arrayValue[6],
    "Field8":arrayValue[7],
    "Field9":arrayValue[8],
    "Field10":arrayValue[9]
      }]
    };
    console.log('req string :' + req);
        fetch('API_URL', {
          headers: {
            'Accept': 'application/json, text/plain, application/xml,  */*',
            'Content-Type': 'application/json' ,
            'Access-Control-Allow-Headers': 'Content-Type',
          },
          method: 'POST',
          body: JSON.stringify(req)}
        ).then(response => {
            if (response.status !== 200) {
              console.log('Problem in fetching');
              return;
            }
            response.text().then(data => {
              console.log('Data in Console',data);
              response_data = data;
              console.log('Response Data',response_data);
              response_jsonObj = JSON.parse(response_data);
              console.log('Response JSON Object',response_jsonObj);
                this.setState({ newData:response_jsonObj});
                //console.log('customer Data in handle submit',customerData);
            });
          }).catch(error => this.setState({ error }));
          }

          handleClick(field1,field2){

            var ID = field1;
            var Name = field2;
            var newresponse_jsonObj,response_data;
            var req ={"GetCustomerRequest": [{
              "field1": field2,
              "field2": "xyz",
              "field3": field1,
              "field4": "",
              "field5": "",
              "field6": ""
              }]
              };
              fetch('API_URL', {
          headers: {
            'Accept': 'application/json, text/plain, application/xml,  */*',
            'Content-Type': 'application/json' ,
            'Access-Control-Allow-Headers': 'Content-Type',
          },
          method: 'POST',
          body: JSON.stringify(req)}
        ).then(response => {
            if (response.status !== 200) {
              console.log('Problem in fetching');
              return;
            }
            response.text().then(data => {
              response_data = data;
              //console.log('Response Data in Handle Click for Get-Customer',response_data);
              newresponse_jsonObj = JSON.parse(response_data);
              console.log('Response JSON Object for Get-Customer',newresponse_jsonObj);
                this.setState({respData:newresponse_jsonObj});
                this.setState({ pageOfItems:newresponse_jsonObj});
                this.getDetails();

            });
          }).catch(error => this.setState({ error }));

          }

          getDetails(){



              console.log('Get Customer Method:');
            <table>
            <tbody>
                 {this.state.pageOfItems.map((item, i) => {
              return (
                 <tr key={i} >
                     <td >{item.XYZ.Field1}</td>
                     <td> {item.XYZ.Field2}</td>
                     <td> {item.XYZ.Field3}</td>
                     <td> {item.XYZ.Field4}</td>
                     <td> {item.Field5}</td>
                 </tr>
              );
            })}
                </tbody>
                  </table>






          }

          searchFunction() {
            var input, filter, table, tr, td, td1, i;
            input = document.getElementById("search");
            filter = input.value.toUpperCase();
            console.log('input in searchFunction:',input);
            console.log('filter in searchFunction:',filter);
            table = document.getElementById("Search-Table");
            console.log('table in searchFunction:',table);
            tr = table.getElementsByTagName("tr");
            var innertext = table.getElementsByTagName("tr").innertext;
            console.log("innertext :",innertext);
            console.log('tr in searchFunction:',tr);
            for (i = 0; i < tr.length; i++) {
              td = tr[i].getElementsByTagName("td")[2];
              console.log('td in for before if:',td);
              if (td) {
                if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
                  tr[i].style.display = "";
                } else {
                  tr[i].style.display = "none";
                }
              }       

            }
        } 


          onSort = (column) => (e) => {
            const direction = this.state.sort.column ? (this.state.sort.direction === 'asc' ? 'desc' : 'asc') : 'desc';
            console.log('direction',direction);
            console.log('column',column);
            const sortedData = this.state.pageOfItems.sort((a, b) => {
              if (column === 'Field1') {
                return a.Field1.toUpperCase().localeCompare(b.Field1.toUpperCase());
              }

              else if (column === 'Last Name') {
                return 

a.Field1.toUpperCase().localeCompare(b.Field1.toUpperCase());
                  }

                });


                if (direction === 'desc') {
                  sortedData.reverse();
                }

                this.setState({
                  pageOfItems: sortedData,
                  sort: {
                      direction,
                        column,
            }
                });
              };

              setArrow = (column,className) => {
                let current_className = className;

                if (this.state.sort.column === column) {
                  current_className += this.state.sort.direction === 'asc' ? ' asc' : ' desc';
                }

                console.log(current_className);

                return current_className;
              };  

          render() {

            var {custID} = this.state;
            return (
              <div id = "id1">
              <div className="row">
                <div className="col-lg-12">
              <PageHeader>Title of The Page </PageHeader>
              </div>
              </div>
            <form onSubmit={this.handleSubmit}>
            <table>
            <tr>
              <td>  
              <FormGroup style={spacing}>
                <ControlLabel>Field1</ControlLabel>
                <FormControl componentClass="select" id="brand"  name="brand" placeholder="select">
                <option value="Value1">Value1</option>
                <option value="Value2">Value2</option>
                <option value="Value3">Value3</option>
                </FormControl>
              </FormGroup>
              </td> 
              <td>
              <FormGroup  style={spacing}>
                <ControlLabel>Field2</ControlLabel>
                <FormControl
                  id="customerId"  name="customerId"
                  type="text"
                  placeholder="Enter Text"
                />
              </FormGroup>
              </td>
              <td>
              <FormGroup style={spacing}>
                <ControlLabel>Field3</ControlLabel>
                <FormControl
                  style={spacing}
                  id="lastname"  name="lastname"
                  type="text"
                  placeholder="Enter Text"
                />
              </FormGroup>
              </td>
              </tr>
              <tr>
              <td>  
              <FormGroup style={spacing}>
                <ControlLabel>Field4</ControlLabel>
                <FormControl
                  id="firstName"  name="firstName"
                  type="text"
                  placeholder="Enter Text"
                />
              </FormGroup>
              </td>
              <td>
              <FormGroup style={spacing}>
                <ControlLabel>Field5</ControlLabel>
                <FormControl
                  id="housenumber"  name="housenumber"
                  type="text"
                  placeholder="Enter Text"
                />
              </FormGroup>
              </td>
              <td>
              <FormGroup style={spacing}>
                <ControlLabel>Field6</ControlLabel>
                <FormControl
                  id="addressline"  name="addressline"
                  type="text"
                  placeholder="Enter Text"
                />
              </FormGroup>
              </td>
              </tr>
              <tr>
              <td>
              <FormGroup style={spacing}>
                <ControlLabel>Field7</ControlLabel>
                <FormControl
                  id="zipcode"  name="zipcode"
                  type="text"
                  placeholder="Enter Text"
                />
              </FormGroup>
              </td>
              <td>
              <FormGroup style={spacing}>
                <ControlLabel>Field8</ControlLabel>
                <FormControl
                  id="email"  name="email"
                  type="text"
                  placeholder="Enter Text"
                />
              </FormGroup>
              </td>
              <td>
              <FormGroup style={spacing}>
                <ControlLabel>Field9</ControlLabel>
                <FormControl
                  id="phonenumber"  name="phonenumber"
                  type="text"
                  placeholder="Enter Text"
                />
              </FormGroup>
              </td>
              </tr>
              <tr>
              <td>  
              <FormGroup style={spacing}>
                <ControlLabel>Field10</ControlLabel>
                <FormControl
                  id="last4digitsphone"  name="last4digitsphone"
                  type="text"
                  placeholder="Enter Text"
                />
              </FormGroup>
              </td>
              <td></td>
              <td>
              <FormGroup style={buttonalignment}>
                <Button bsStyle="primary" type="submit">Search </Button>
                {'  '}
                <Button bsStyle="primary" type="reset">Clear </Button>
              </FormGroup>
              </td>
              </tr>
            </table>

              <div className="row ng-scope">
                <div className="col-lg-15">
                  <Panel header={<span> Search Results</span>} >
                  <div id="dataTables-example_filter" className="dataTables_filter">
                             <label htmlFor={'search'}>Search:
                               <input
                                 type="text"
                                 className="form-control input-sm"
                                 placeholder=""
                                 aria-controls="dataTables-example"
                                 id="search" onKeyUp={this.searchFunction}
                               />
                             </label>
                           </div><br></br>
                  <div id ="Search-Table" className="table-responsive">
                    <table className="table table-striped table-bordered table-hover dataTable no-footer" id="dataTables-example"  role="grid" aria-describedby="dataTables-example_info">
                    <thead>
                           <tr role="row">
                             <th>Field1</th>
                             <th>Field2</th>
                             <th className="sorting" onClick={this.onSort('Field 3','asc')} aria-sort="ascending"
                            aria-label="Rendering engine: activate to sort column descending"
                            aria-controls="dataTables-example"
                            rowSpan="1"
                            colSpan="1"
                            tabIndex="0">Field3<span className={this.setArrow('First Name')}></span></th>
                             <th className="sorting" onClick={this.onSort('Field 4','asc')}>Last Name <span className={this.setArrow('Field 4')}></span></th>
                             <th>Field3</th>
                             <th>Field4</th>
                             <th>Field5</th>
                             <th>Field6</th>
                             <th>Field7</th>
                             <th>Field8</th>
                             <th>Field9</th>
                          </tr>
                         </thead>
                     <tbody>
                     {this.state.pageOfItems.map((item, i) => {
                  return (
                     <tr key={i} onClick={()=>this.handleClick(item.Field1,item.Field2)}>
                         <td >{item.Field1}</td>
                         <td> {item.Field2}</td>
                         <td> {item.Field3}</td>
                         <td> {item.Field4}</td>
                         <td> {item.Field5}</td>
                         <td> {item.Field6}</td>
                         <td> {item.Field7}</td>
                         <td> {item.Field8}</td>
                         <td> {item.Field9}</td>
                         <td> {item.Field10}</td>
                         <td> {item.Field11}</td>
                     </tr>
        );
                })}
                    </tbody>
                      </table>
                      <div className="col-sm-6 pullRight " >
                      <JwPagination  items={this.state.newData} onChangePage={this.onChangePage} /> 
                      </div>   
                      </div>
                      </Panel>
                      </div>
                      </div>
              </form>
    <DisplayDetails respData={this.state.respData}/>
        </div>

        );
         }
          }
        export default displayBlank;

    DisplayDetails.js

    import React, { PropTypes , Component } from 'react';


    class displayDetails extends Component {


     render() {
       return <h1 >Hello World!</h1>
       {this.props.respData.map((item, i) => {
        return (
           <tr key={i} >

               <td >{item.FIELD1}</td>
               <td> {item.FIELD2}</td>
           </tr>
    );
      })}

<div className="col-lg-6">
<Panel header={<span>add</span>} >
<div className="table-responsive">
  <table className="table table-striped table-bordered table-hover">
    <thead>
      <tr>
        <th> FIELD 1 </th>
        <th> FIELD 2 </th>
        <th> FIELD 3 </th>
        <th> FIELD 4</th>
        <th> FIELD 5 </th>
        <th> FIELD 6</th>
      </tr>
    </thead>
    <tbody>
    {Object.keys(addData).map((item, i) => {
          return (
            <tr key={i}>  
                          <td> {addData[item].FIELD1}</td>
                 <td> {addData[item].FIELD2}</td>
                 <td> {addData[item].FIELD3}</td>
                 <td> {addData[item].FIELD4}</td>
                 <td> {addData[item].FIELD5}</td>
                 <td> {addData[item].FIELD6}</td>
             </tr>
);
        })}
    </tbody>
  </table>
</div>
</Panel>
</div>

      }

    }


    export default displayDetails;


class Phone extends React.Component {

  constructor(props) {
    super(props);

    //  this.state.phones = [];
    this.state = {};
    this.state.filterText = "";
    this.state.phones = [
      {
        id: 1,
       Field1: '',
       Field2: '',
       Field3: '',
       Field4: '',
       Field5: ''
      }
    ];

  }
  handleUserInput(filterText) {
    this.setState({filterText: filterText});
  };
  handleRowDel(phone) {
    var index = this.state.phones.indexOf(phone);
    this.state.phones.splice(index, 1);
    this.setState(this.state.phones);
  };

  handleAddEvent(evt) {
    var id = (+ new Date() + Math.floor(Math.random() * 999999)).toString(36);
    var phone = {
      id: id,
      Phone_Number: '',
       Type: '',
       Receive_Calls: '',
       Receive_Texts: '',
       Preferred_Phone_Number: ''

    }
    this.state.phones.push(phone);
    this.setState(this.state.phones);

  }

  handlephoneTable(evt) {
    var item = {
      id: evt.target.id,
      name: evt.target.name,
      value: evt.target.value
    };
    console.log('item.value in phone',item.value);
var phones = this.state.phones.slice();
  var newphones = phones.map(function(phone) {

    for (var key in phone) {
      if (key == item.name && phone.id == item.id) {
        phone[key] = item.value;

      }
    }
    return phone;
  });
    this.setState({phones:newphones});
  //  console.log(this.state.phones);
  };
  render() {

    return (
      <div>

        <PhoneTable onphoneTableUpdate={this.handlephoneTable.bind(this)} onRowAdd={this.handleAddEvent.bind(this)} onRowDel={this.handleRowDel.bind(this)} phones={this.state.phones} filterText={this.state.filterText}/>
      </div>
    );

  }

}


class PhoneTable extends React.Component {

  render() {
    var onphoneTableUpdate = this.props.onphoneTableUpdate;
    var rowDel = this.props.onRowDel;
    var filterText = this.props.filterText;
    var phone = this.props.phones.map(function(phone) {
      if (phone.Type.indexOf(filterText) === -1) {
        return;
      }
      return (<PhoneRow onphoneTableUpdate={onphoneTableUpdate} phone={phone} onDelEvent={rowDel.bind(this)} key={phone.id}/>)
    });
    return (
      <div>

    <th>Phone</th>
      <button type="button" onClick={this.props.onRowAdd} className="btn btn-success pull-right">Add</button>
        <table className="table table-bordered">
          <thead>
            <tr>
              <th>Phone_Number</th>
              <th>Type</th>
              <th>Receive_Calls</th>
              <th>Receive_Texts</th>
              <th>Preferred_Phone_Number</th>
            </tr>
          </thead>

          <tbody>
            {phone}

          </tbody>

        </table>
      </div>
    );

  }

}

class PhoneRow extends React.Component {
  onDelEvent() {
    this.props.onDelEvent(this.props.phone);

  }
  render() {

    return (
      <tr className="eachRow">
        <EditableCell onphoneTableUpdate={this.props.onphoneTableUpdate} cellData={{
          "type": "Field1",
          value: this.props.phone.Field1,
          id: this.props.phone.id
        }}/>
        <EditableCell onphoneTableUpdate={this.props.onphoneTableUpdate} cellData={{
          type: "Field2",
          value: this.props.phone.Field2,
          id: this.props.phone.id
        }}/>
        <EditableCell onphoneTableUpdate={this.props.onphoneTableUpdate} cellData={{
          type: "Field3",
          value: this.props.phone.Field3,
          id: this.props.phone.id
        }}/>
        <EditableCell onphoneTableUpdate={this.props.onphoneTableUpdate} cellData={{
          type: "Field4",
          value: this.props.phone.Field4,
          id: this.props.phone.id
        }}/>
        <EditableCell onphoneTableUpdate={this.props.onphoneTableUpdate} cellData={{
          type: "Field5",
          value: this.props.phone.Field5,
          id: this.props.phone.id
        }}/>
        <td className="del-cell">
          <input type="button" onClick={this.onDelEvent.bind(this)} value="REMOVE" className="del-btn"/>
        </td>
      </tr>
    );

  }

}
class EditableCell extends React.Component {

  render() {
    return (
      <td>
        <input type='text' name={this.props.cellData.type} id={this.props.cellData.id} value={this.props.cellData.value} onChange={this.props.onphoneTableUpdate}/>
      </td>
    );

  }

}


export default Phone;

1 个答案:

答案 0 :(得分:0)

您可以使用上下文来传递道具。 Here是官方文档的链接。

上下文旨在共享可被视为React组件树的“全局”数据。