将参数传递给React Native中的组件

问题描述 投票:22回答:3

我正在尝试使用我在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}>&#xf0c9;</Button>}
                rightButton={<Button style={styles.menuButton}>&#xf07a;</Button>} />
        );
    }
});

在另一页上应用它:

<NavigationBar title="Categories" titleColor="#ffffff" NavBarColor="#f0b210"/>

如何正确执行此操作?预先感谢。

javascript react-native react-jsx
3个回答
29
投票

首先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);

7
投票

您可以调用导航栏组件并提供类似的道具

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}>&#xf0c9;</Button>}
            rightButton={
                <Button style={styles.menuButton}>&#xf07a;</Button>}
             />
    );
}

随着颜色和标题的更改,效果钩将使用状态钩触发并更新标题和颜色的状态,这将强制组件以更新的值重新呈现。因此,它的一种方法绑定为您提供了一种风味双向绑定。


1
投票

render是一个非参数化函数,表示它没有任何参数。因此,要在React Native中将参数/值从一个组件传递到另一个组件,我们使用propsprops是一个JavaScript对象,具有可从一个组件传递到另一个组件的属性。因此,您需要使用props

传递值。
© www.soinside.com 2019 - 2024. All rights reserved.