0

我正在自学 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使用 state渲染组件2

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

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

4

1 回答 1

1

不确定 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} />
  }
}
于 2018-03-24T07:04:06.757 回答