简体   繁体   中英

Using React state in other components

I'm having trouble accessing the state stored in my App.js file in another component, Capacity.js.

I followed the official React documentation to move state up, as I will need it in other components.

Here's my App.js file:

import React, { Component } from 'react'
import Cylinders from './Cylinders'
import Capacity from './Capacity'

class App extends Component {
  constructor(props) {
    super(props);
    this.handleCapacityChange = this.handleCapacityChange.bind(this);
    this.state = {
      capacity: 2
    }
  }

  handleCapacityChange(capacity){
    this.setState({capacity})
  }

  render() {
    return (
      <div className="App">
        <h1>Engine power</h1>
        Select the number of cylinders:
        <Cylinders/>
        Enter the capacity:
        <Capacity
        onCapacityChange={this.handleCapacityChange} />
      </div>
    )
  }
}

export default App

And here is my Capacity.js file:

import React, { Component } from 'react'

class Capacity extends Component {
  constructor(props) {
    super(props);
  }

  onInput() {
    var input = document.getElementById("capinp");
    var cap = input.value;
    this.props.onCapacityChange(parseFloat(cap))
}

  render() {
   return (
     <form name="capacity">
     <input id="capinp" type="range" min="1" max="7" step="0.1" defaultValue="2" onInput={this.onInput.bind(this)}/>
     </form>
  )
 }
}

export default Capacity

Now my understanding from what I have read is that I should be able to use {this.props.capacity} within the render function of Capacity.js like below.

  render() {
   return (
     <form name="capacity">
     <input id="capinp" type="range" min="1" max="7" step="0.1" defaultValue="2" onInput={this.onInput.bind(this)}/>
     {this.props.capacity}
     </form>
  )
 }

This isn't recognised and doesn't display anything. I am new to React so I apologise if I have done something glaringly obvious or fundamentally wrong.

You will need to pass the capacity state from the parent component to the Capacity component as part of its props.

render() {
  const { capacity } = this.state
  return (
     // others
     <Capacity
       capacity={capacity}
       onCapacityChange={this.handleCapacityChange} 
    />
  )

}

And on your Capacity component,

render() {
  const { capacity } = this.props;

  return (
    <form name="capacity">
      <input id="capinp" type="range" min="1" max="7" step="0.1" defaultValue="2" onInput={this.onInput.bind(this)}/>
      {capacity}
    </form>
  )
}

Send capacity from App.js to Capacity.js

       <Capacity
        capacity={this.state.capacity}
        onCapacityChange={this.handleCapacityChange} 
       />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM