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

p/react:使用“标记”语法时无法访问状态

  •  0
  • clo_jur  · 技术社区  · 7 年前

    我在自学p/react,我不确定为什么我不能访问组件的状态。

    我有一个组件:

    const AView = (state,props) => (
      <div>
        <p>{state.a}</p>
        <B />
      </div>
    )
    
    class A extends Component {
      constructor() {
        super();
        this.state = { a: 1 };
      }
      render(props,state) {
        return <AView a={state.a}/>
      }
    }
    
    const BView = (state,props) => (
      <div>
        <p>{state.b}</p>
      </div>
    )
    
    class B extends Component {
      constructor() {
        super();
        this.state = { b: 2 };
      }
      render(props,state) {
        return <BView b={state.b}/>
      }
    }
    

    这将渲染组件 A 具有预期状态 1 ,但它不渲染组件 B 带状态 2 (组件 B 只是渲染为空 <p> 标签)。

    然而,如果我使用另一种语法,我可以渲染组件 B 带状态 2. :

    class B extends Component {
      ...
      render(props,state) {
        return BView(props,state);
      }
    }
    

    我是在概念上遗漏了什么,还是只是一些语法我不知道?我试过在谷歌上搜索,但我真的不知道足够的术语来获得相关的搜索结果。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Tomasz Mularczyk    7 年前

    不确定Preact。但我会尝试这样修复它:

    const AView = (props) => (
      <div>
        <p>{props.text}</p>
        <BView />
      </div>
    )
    
    class A extends Component {
      constructor() {
        super();
        this.state = { a: 1 };
      }
      render() {
        return <AView text={this.state.a} />
      }
    }
    
    const BView = (props) => (
      <div>
        <p>{props.text}</p>
      </div>
    )
    
    class B extends Component {
      constructor(props) {
        super(props);
        this.state = { b: 2 };
      }
      render() {
        return <BView text={this.state.b} />
      }
    }