我正在尝试使用我在React-Native中制作的通用导航组件。在通话时,我想设置导航栏的色调,标题等。
导航条形码:
var NavigationBar = React.createClass({
render: function(title, titleColor, NavBarColor) {
var titleConfig = {
title: title,
tintColor: titleColor,
};
return (
<NavBar
title={titleConfig}
tintColor={NavBarColor}
leftButton={<Button style={styles.menuButton}></Button>}
rightButton={<Button style={styles.menuButton}></Button>} />
);
}
});
在另一页上应用它:
<NavigationBar title="Categories" titleColor="#ffffff" NavBarColor="#f0b210"/>
如何正确执行此操作?预先感谢。
首先render
不带任何参数,您要做的是引用传入的道具。
render: function () {
var titleConfig = {
title: this.props.title,
tintColor: this.props.titleColor
};
// Rest of code
}
只需执行此操作,只要NavigationBar
重新发布,NavBar
组件也会重新发布。
展示这个的超级简单示例
var NavBar = React.createClass({
render: function () {
return <div id="navbar" style={{backgroundColor: this.props.tintColor}}>
<h1 style={{color: this.props.title.tintColor}}>{this.props.title.title}</h1>
</div>;
}
});
var NavigationBar = React.createClass({
render: function() {
var titleConfig = {
title: this.props.title,
tintColor: this.props.titleColor,
};
return (
<NavBar
title={titleConfig}
tintColor={this.props.NavBarColor}
/>
);
}
});
React.render(<NavigationBar title="Categories" titleColor="#ff0" NavBarColor="#f0b210" />, document.body);
您可以调用导航栏组件并提供类似的道具
let inputProps={
color:"blue",
title:"Title"
};
<NavigationBar props={inputProps}/>
并且在NavigationBar的声明中,您可以像这样使用它
const NavigationBar = (props)=>{
const [title,setTitle] = useState("");
const [color,setColor] = useState("");
useEffect(()=>{
setColor(props.color);
setTitle(props.title);
},[props.color,props.title]);
return(
<NavBar
title={title}
tintColor={color}
leftButton={<Button style={styles.menuButton}></Button>}
rightButton={
<Button style={styles.menuButton}></Button>}
/>
);
}
随着颜色和标题的更改,效果钩将使用状态钩触发并更新标题和颜色的状态,这将强制组件以更新的值重新呈现。因此,它的一种方法绑定为您提供了一种风味双向绑定。
render是一个非参数化函数,表示它没有任何参数。因此,要在React Native中将参数/值从一个组件传递到另一个组件,我们使用props。 props是一个JavaScript对象,具有可从一个组件传递到另一个组件的属性。因此,您需要使用props。
传递值。