将值从一个组件传递到另一个组件

时间:2018-06-07 12:28:32

标签: javascript reactjs

我将地址存储在变量中,然后通过以下方式将其发送到另一个组件:



this.setState({
  place_formatted: place.formatted_address,
  place_id: place.place_id,
  place_location: location.toString(),

});
var addr= place.formatted_address;
  console.log(addr);
  <Tab test={this.props.addr}/>
&#13;
&#13;
&#13;

并且在表格组件中我称之为:

&#13;
&#13;
class Tab extends React.Component {
render() {
const items = this.props.items;
const test2 = this.props.addr;
console.log(test2);
&#13;
&#13;
&#13;

但表组件中的console.log显示未定义的值。我的问题是如何解决这个问题?

感谢任何帮助。

谢谢。

整码

Form.js

&#13;
&#13;
import React, { Component } from 'react';

import { Table, Alert, Button,  Label, Input} from 'reactstrap';
import './MapStyle.css';
import Tab from './Table';

class Form extends React.Component {
  constructor() {
  super();
  this.state = {
    zoom: 13,
    maptype: 'roadmap',
    place_formatted: '',
    place_id: '',
    place_location: '',
  };
}
componentDidMount() {
  let map = new window.google.maps.Map(document.getElementById('map'), {
    center: {lat: 22.7196, lng: 75.8577},
    zoom: 13,
    mapTypeId: 'roadmap',
  });

  map.addListener('zoom_changed', () => {
  this.setState({
    zoom: map.getZoom(),
  });
});

map.addListener('maptypeid_changed', () => {
  this.setState({
    maptype: map.getMapTypeId(),
  });
});
let marker = new window.google.maps.Marker({
map: map,
position: {lat: -33.8688, lng: 151.2195},
});

// initialize the autocomplete functionality using the #pac-input input box
let inputNode = document.getElementById('pac-input');

let autoComplete = new window.google.maps.places.Autocomplete(inputNode);

autoComplete.addListener('place_changed', () => {
let place = autoComplete.getPlace();
let location = place.geometry.location;

this.setState({
  place_formatted: place.formatted_address,
  place_id: place.place_id,
  place_location: location.toString(),

});
var addr= place.formatted_address;
  console.log(addr);
  <Tab test={this.props.addr}/>

// bring the selected place in view on the map
map.fitBounds(place.geometry.viewport);
map.setCenter(location);

marker.setPlace({
  placeId: place.place_id,
  location: location,
});
});
}

render() {

  return (


    <div id="Form" >
      {/*Form Layout*/}


      <Alert color="primary">
        Add Your Vehicle!
      </Alert>

        <form onSubmit={this.props.handleFormSubmit}>
            <Label htmlFor="name"></Label>

                <Input id="name" placeholder="Name" value={this.props.newname}
                 type="text" name="name" onChange={this.props.handleInputChange} />


            <Label htmlFor="origin"></Label>

              <Input type="select" id="origin" name="origin" value={this.props.neworigin}
               onChange={this.props.handleInputChange}>
               <option>Origin</option>
               <option value="Sarda House">Sarda House</option>
               <option value="Crystal IT Park">Crystal IT Park</option>
               <option value="Impetus IT Park">Impetus IT Park</option>
              </Input>


            <Label htmlFor="destination"></Label>


                 <Input id="pac-input"
                  type="text" name="destination" placeholder="Destination"  onChange={this.props.handleInputChange} />


            <Label htmlFor="seats"></Label>

              <Input type="select" id="seats" name="seats" value={this.props.newseats}
               onChange={this.props.handleInputChange}>

               <option>Seats Available</option>
               <option value="1">1</option>
               <option value="2">2</option>
               <option value="3">3</option>
               <option value="4">4</option>
               <option value="5">5</option>
               <option value="6">6</option>
               <option value="7">7</option>
               <option value="8">8</option>
                  </Input>

    <Label htmlFor="submit"></Label>
            <Button type="submit" value="submit" color="danger" size="lg" block >Add Your Vehicle</Button>

        </form><br></br>


<div>
<div id='map' />
</div>
            </div>




    );
  }
}
export default Form;
&#13;
&#13;
&#13;

Table.js

&#13;
&#13;
import React, { Component } from 'react';
import { Table, Alert } from 'reactstrap';
import Form from './Form';

class Tab extends React.Component {
render() {
const items = this.props.items;
const test = this.props.test;
console.log(test);
items.sort((a,b) => {
const name1 = a.name.toLowerCase(), name2 = b.name.toLowerCase();
return name1 === name2 ? 0 : name1 < name2 ? -1 : 1;  });


return (

      <Table bordered>
        {/*Table Heading*/}
           <thead>
                <Alert color="primary"> <tr>
                 <th>Name</th>
                 <th>Origin</th>
                 <th>Destination</th>
                 <th>Seats Available</th>
               </tr></Alert>
             </thead>
             <tbody>
             {items.map(item => {
  return (

           <tr>
               {/*Table rows and Columns*/}
                 <td>{item.name}</td>
                 <td>{item.origin}</td>
                 <td>{this.props.destination}</td>
                 <td>{item.seats}</td>
               </tr>
          );
              })}
             </tbody>
        </Table>

    );
  }
}
export default Tab;
&#13;
&#13;
&#13;

App.js

&#13;
&#13;
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import Navb from './Navbar';

import Tab from './Table';
import Form from './Form';
import './NavStyle.css';
class App extends Component {
  state = { showing: true };

constructor() {
  super();

  this.state = {
    name: '',
    origin: '',
      destination: '',
        seats: '',
    items: []
  }
};

handleFormSubmit = (e) => {
  e.preventDefault();
  console.log('submit');
  let items = [...this.state.items];

  items.push({
    name: this.state.name,
    origin: this.state.origin,
    destination: this.state.destination,
    seats: this.state.seats
  });

  this.setState({
    items,
    name: '',
    origin: '',
    destination: '',
    seats: ''
  });
};

handleInputChange = (e) => {
  let input = e.target;
  let name = e.target.name;
  let value = input.value;

  this.setState({
    [name]: value
  })
};
  render() {
      const { showing } = this.state;
    return (
      <div>
      <Navb/>
      <br></br>
      <div className="navbar-header">
            <ul className="header">
        <li>  <a href="javascript:void(0)"    onClick={() => this.setState({ showing: !showing })}>
          Add Carpool
          </a></li>

          <li><a href="javascript:void(0)"   onClick={() => this.setState({ showing: !showing })}>
        Find Carpool
          </a></li>
              </ul>


        </div>



                                     { showing

                                         ?  <Tab items={ this.state.items }/>

                                         : <Form handleFormSubmit={ this.handleFormSubmit }
                                            handleInputChange={ this.handleInputChange }
                                            newName={ this.state.name }
                                            newOrigin={ this.state.origin }
                                            newDestination={ this.state.destination }
                                            newSeats={ this.state.seats } />

                                     }

              </div>


    );
  }
}

export default App;
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:1)

在标签组件中,道具以test传递,因此请尝试

class Tab extends React.Component {
render() {
console.log(this.props.test);

Edit vy657ok5jy

答案 1 :(得分:1)

您需要将<Tab />组件移至render()组件的Form方法,并从州传递place_formatted值。

如果您愿意,可以添加其他检查place_formatted是否为空。

以下是代码:

<强> Form.jsx

class Form extends React.Component {
    ...all the code

    render() {
      const { place_formatted } = this.state
      return (
          ...
          { place_formatted && 
             <Tab test={place_formatted} />
          }
          ...
      )
    } 
}

在这种情况下,您可以将Tab组件中的此值设为this.props.test

答案 2 :(得分:0)

change test = {this.props.addr} - &gt; ADDR = {}地址

&#13;
&#13;
this.setState({
  place_formatted: place.formatted_address,
  place_id: place.place_id,
  place_location: location.toString(),

});
var addr= place.formatted_address;
  console.log(addr);
  <Tab addr={addr}/>
&#13;
&#13;
&#13;