Reactjs p/react:使用“标记”语法时无法访问状态
我在自学p/react,我不确定为什么不能访问组件的状态 我有一个组成部分:Reactjs p/react:使用“标记”语法时无法访问状态,reactjs,react-props,preact,Reactjs,React Props,Preact,我在自学p/react,我不确定为什么不能访问组件的状态 我有一个组成部分: const AView = (state,props) => ( <div> <p>{state.a}</p> <B /> </div> ) class A extends Component { constructor() { super(); this.state = { a: 1 }; } re
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}/>
}
}
我是在概念上遗漏了什么,还是只是一些语法我不知道?我试过在谷歌上搜索,但我真的不知道足够的术语来获得相关的搜索结果。不确定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} />
}
}
你是否正在渲染,并想知道为什么内部不会渲染state.b或其他东西?@Deryck。对我想知道为什么在呈现视图时我不能看到BView状态,除非我将BView作为显式函数返回。该状态确实是组件的本地状态。但在您的示例中,您试图使用父组件中存在的状态。这就是为什么你需要把它作为道具传下去。
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} />
}
}