在其他组件中使用React状态

时间:2020-05-16 13:52:25

标签: javascript reactjs

我无法访问存储在另一个组件Capacity.js中App.js文件中的状态。

我遵循了React的官方文档以提高状态,因为在其他组件中将需要它。

这是我的App.js文件:

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

这是我的Capacity.js文件:

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

现在,据我所了解的是,我应该能够在Capacity.js的呈现函数中使用{this.props.capacity},如下所示。

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

无法识别,不显示任何内容。我是React的新手,所以如果我做过明显或明显错误的事情,我深表歉意。

2 个答案:

答案 0 :(得分:0)

作为道具的一部分,您需要将capacity状态从父组件传递到Capacity组件。

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

}

在您的Capacity组件上,

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

答案 1 :(得分:0)

将容量从App.js发送到Capacity.js

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