首页 > 解决方案 > 将值从一个组件传递到另一个 React

问题描述

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

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

在表组件中,我这样称呼它:

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

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

任何帮助表示赞赏。

谢谢你。

完整代码

表单.js

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;

表.js

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;

应用程序.js

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;

标签: javascriptreactjs

解决方案


在 Tab 组件中,该 prop 被传递,test因此尝试

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

编辑 vy657ok5jy


推荐阅读