【发布时间】:2018-09-28 20:16:44
【问题描述】:
我是异步机制的 reactnative/js 世界的新手,我阅读了很多类似的示例,但我不清楚。所以请在这里找到我的问题。
我正在尝试创建一个组件(在示例中称为“锚”)并从另一个组件更新其状态(名称参数)。 我想从父组件中获取“锚”组件的属性 state.name 值。 我的问题如下: - 锚组件的创建似乎没有处理组件创建的 props.name 参数 - 不知道如何从父组件(示例中的App)访问组件状态参数值(his.state.name)
https://jsfiddle.net/n5u2wwjg/203556/
锚组件
class Anchor extends React.Component{
constructor(props) {
super(props)
this.state = {
name : props.name
}
this.name = this.state.name;
}
/*
getName(){
return this.state.name;
}
*/
}
以及 App 组件:
class App extends React.Component <any> {
constructor(props) {
super(props)
this.state = {
anchor : undefined,
items: [
{ text: "Learn JavaScript", done: false },
{ text: "Learn React", done: false },
{ text: "Play around in JSFiddle", done: true },
{ text: "Build something awesome", done: true }
]
}
}
addAnchor(){
var anchor = new Anchor('hello');
this.setState({
anchor : anchor,
});
console.debug('get my anchor name: '+ this.state.anchor.name);
}
render() {
return (
<div>
<h2>Todos:</h2>
{this.state.anchor.name}
<ol>
{this.state.items.map(item => (
<li key={item.id}>
<label>
<input type="checkbox" disabled readOnly checked={item.done} />
<span className={item.done ? "done" : ""}>{item.text}</span>
</label>
</li>
))}
</ol>
</div>
)}
}
【问题讨论】:
-
不要用 props 初始化 state。
-
我也尝试使用其他函数来更新状态(调用 SetState),但它不起作用。
-
将父状态作为道具传递......然后传递另一个道具......一个函数。这是一个例子.....
<Anchor name={this.state.name} changeName={newName => this.setState({name: newName})} />inside anchor 像这样使用 thise....this.props.name访问名称,this.props.changeName("example")将名称更改为示例
标签: reactjs react-native