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

Passing Parameters to Components in React Native

我正在尝试使用我在 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"/>

如何正确执行此操作?提前致谢。

您可以这样调用导航栏组件并赋予道具

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>}
             />
    );
}

随着颜色和标题的变化,效果挂钩将触发并使用状态挂钩更新标题和颜色的状态,这将强制组件 re-render 更新 values.So 它的一种方式绑定给你一种双向绑定的感觉。

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

render 是一个非参数化函数,意味着它不接受任何参数。因此,为了在 React Native 中将 parameters/value 从一个组件传递到另一个组件,我们使用 propsprops 是一个 JavaScript 对象,它有 属性 从一个组件传递到其他组件。 因此,您需要使用 props.

传递值