我是React-Native的新手,它是我的第一个React-Native应用。但是,我已经遇到了一些问题。
我想将一个变量从一个类(Home.js)传递给另一个类。 (是否可以不在render()函数中使用composent?)
##### Home.js #####
class Home extends Component {
constructor(props) {
super(props);
this.state = {direction: "defaultvalue"};
}
getCurrentDirection() {
return this.state.direction;
}
render() {
/***..... some elements ..*/
}
}
export default Home
并且
#### Two.js ####
import Home from './Home'
/** SOME CODE **/
const DrawerOptions = {
initialRouteName: Home.getCurrentDirection(),
contentComponent: CustomDrawerContentComponent,
drawerWidth: 300,
};
然而它不起作用......如何解决?我已经尝试了一些解决方案,因为将getCurrentDirection声明为静态但没有。
此外,它似乎是一个特定的情况,因为DrawerOptions不是一个类。你能不能加入你的回复,如果我想把变量加到Two.js类中怎么做? 我的意思是如果Two.js是例如:
##### Two.js #####
class Two extends Component {
var myvariable = Home.getCurrentDirection();
render() {
/***..... some elements ..*/
}
}
提前多多感谢
答案 0 :(得分:1)
从组件访问状态到另一个组件的可推荐方法是使用(在这种情况下)Home
组件作为Two
组件的父组件。这样您就不必触发函数来访问Home
的状态。每次更新父组件(在本例中)组件的状态时,Two
组件将收到更新的属性(方向)。如果要从Two
组件调用函数,则必须将其作为属性( changeCurrentDirection )传递给函数,该函数将从{{1}调用要调用的函数。 } 零件。
所以你会有这样的事情:
Home
class Home extends React.Component {
constructor(props) {
super(props);
this.state = {
direction: "defaultValue"
};
}
changeCurrentDirection() {
this.setState({
direction: "valueChanged"
})
}
render() {
let state = this.state;
return (
<Two
direction={state.direction}
changeCurrentDirection={() => this.changeCurrentDirection.bind(this)}/>
)
}
}
class Two extends React.Component {
render() {
let props = this.props;
return (
<div>
<h3>{props.direction}</h3>
<button onClick={props.changeCurrentDirection()}>Change value</button>
</div>
)
}
}
React.render(<Home/> , document.getElementById('app'));
您可以找到here的其他信息。
另外,如果您希望对组件的状态进行良好的管理,我的建议是使用redux。使用此库,您可以轻松连接组件的操作和属性,这些操作和属性可以从您可以管理它们的其他文件中进一步访问。