如何将状态值作为道具传递给子组件

时间:2021-05-27 13:00:54

标签: javascript reactjs

我试图将一些存储在父组件状态中的常量值传递给子组件,并希望在树中向下传递。

  1. 在 App.tsx 状态或任何其他建议中存储常量值是否正确
  2. 我如何从 App.tsx 访问 GrTag 或 sTag 到 Subchild 组件。

App.tsx

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
        sTag : "00D",
        pTag : "010",
        adTag : "020",
        dbTag : "030",
        GrTag : "040",
        serTag : "00E",
        modTag : "060",
        iTag: "018"
      };
  }
  render() {
        return(
          <div >
            <Child {...this.state}/>  //is this right way to pass
          </div>
        );
  }
}

Child.tsx

class Child extends Component {
  constructor(props) {
    super(props);
  }
  render(){
      return(
        <div>
        {
          <Subchild />    //want to pass the state values from App.tsx 
        }
        </div>
      );
  };
}

Subchild.tsx

class Subchild extends Component {
  constructor(props) {
    super(props);
  }
  render(){
      return(
        <div>
        {
            // want to print sTag value here
        }
        </div>
      );
  };
}

3 个答案:

答案 0 :(得分:2)

您传播状态 {...this.state} 的方式会将所有状态值作为道具传递给子组件。如果您需要 Child 组件中的所有状态值作为道具,那么您所做的就很好。

但是如果您只需要 subChild 内的 stag 中的 App 那么您可以这样做

<Child {...this.state}/> 

在你的 Child.tsx 中

<Subchild {...this.props} />

答案 1 :(得分:1)

要解决您的问题,请将道具从孩子传递给子孩子。像这样;

class Child extends Component {
  constructor(props) {
    super(props);
  }
  render(){
      return(
        <div>
        {
          <Subchild {...this.props}/>    //want to pass the state values from App.tsx 
        }
        </div>
      );
  };
}

但是请注意。这不是将数据传递给组件的好方法。 如果您的数据可以在应用中的多个组件之间共享,请考虑使用 REACT REDUXMOBX。我个人推荐使用 Redux。

答案 2 :(得分:1)

App.tsx

class App extends Component {
constructor(props) {
super(props);
this.state = {
    sTag : "00D",
    pTag : "010",
    adTag : "020",
    dbTag : "030",
    GrTag : "040",
    serTag : "00E",
    modTag : "060",
    iTag: "018"
  };
}
render() {
    return(
     const data = this.state;
      <div >
        <Child dataToClid = {data}/>  //is this right way to pass
      </div>
    );
 }
}

Child.tsx

class Child extends Component {
 constructor(props) {
   super(props);
   this.state = {
        data: this.props.dataToClid
    }
 }
 render(){
  const data = this.state;
  return(
    <div>
    {
      <Subchild dataToSubClid = {data}/>    //want to pass the state values from App.tsx 
    }
    </div>
  );
 };
}

SubChild.tsx

class Subchild extends Component {
  constructor(props) {
     super(props);
     this.state = {
        data: this.props.dataToSubClid
     }
  }
  render(){
    const {GrTag, sTag} = this.state;
    return(
      <div>
       <p>{GrTag}</p>
       <p>{sTag}</p>
      </div>
    );
 };
}

您可以这样做,也可以使用Context API 将数据从父级传递给子级