代码之家  ›  专栏  ›  技术社区  ›  mdash1

使用props从子类访问/更改父类状态(React)

  •  1
  • mdash1  · 技术社区  · 7 年前

    我试图设置父类和子类的状态。但是很难想出怎么做。我已经把我认为与手头的问题无关的任何东西都抽象出来了。问题是我

    Class Parent extends Component {
         constructor(props){
          super(props)
           this.state = {
             foo: "bar"
           }
         }
         coolMethod(n){
            this.setState({foo: n})
         }
         render{
            return(
              <Child coolmethod={this.coolMethod} />
             )
          }
    }
    
    Class Child extends Component {
         constructor(props){
          super(props)
         }
         componentDidMount(){ 
          let that = this;
           videojs('my-player', options, function onPlayerReady() {
             this.on('end',()=>{
               that.props.coolMethod(<whatever string returns as a result of 
               this method>)
             })
           })
         }
         render{
            return(
              // irrelevant stuff to this question
             )
          }
    }
    

    如果您想了解有关videojs的更多信息: http://videojs.com/ (虽然这与问题本身无关,但我在孩子的videojs call-in-componentDidMount中引用了它)

    2 回复  |  直到 7 年前
        1
  •  2
  •   An Nguyen    7 年前

    我想第二节课是 Class Child extends Component ... this.coolMethod 在你的 Parent 构造函数优先。

    Class Parent extends Component {
         constructor(props){
          super(props)
           this.state = {
             foo: "bar"
           }
           
           this.coolMethod = this.coolMethod.bind(this);
         }
         
         coolMethod(n){
            this.setState({foo: n})
         }
         render{
            return(
              <Child coolmethod={this.coolMethod} />
             )
          }
    }
        2
  •  0
  •   Jacky Choo    7 年前

    1. coolmethod 传递给孩子,但你正在尝试访问 coolMethod .
    2. this.coolMethod = this.props.coolMethod.bind(this); 否则, this 内部 coolMethod方法 将未定义。

      import React, { Component } from 'react';
      
      export default class Parent extends Component {
        constructor(props){
          super(props)
          this.state = {
            foo: "bar"
          }
        }
      
        coolMethod(n){
            this.setState({foo: n})
        }
      
        render(){
            return(
              <Child coolMethod={this.coolMethod} />
            )
          }
      }
      
      class Child extends Component {
        constructor(props){
          super(props)
          this.coolMethod = this.props.coolMethod.bind(this);
        }
      
        render(){
            return(
              <button onClick={() => this.coolMethod("aabbcc")}>1</button>
            )
          }
      }