javascript - 如何将 props 传递给 Material-ui 风格的组件?

标签 javascript node.js reactjs material-ui

我有一个组件,我也想传递 props,但是这个组件也有内部 props 来处理样式,我不知道如何处理这两个。

这就是我目前拥有的。

const styles = theme => ({
    // Theme building
});

const LoginLink = React.forwardRef((props, ref) => (
    <Link innerRef={ref} to="/login" {...props} />
));

const HomeLink = React.forwardRef((props, ref) => (
    <Link innerRef={ref} to="/" {...props} />
));

const NavBar = (props) => {

    const {classes} = props;

    // Some functions

    return(

        // Some code

        {props.isAuthenticated
                ? <Button color="inherit" onClick={handleLogout}>Logout</Button>
                : <Button color="inherit" component={LoginLink}>Login</Button>
        }
    );
}

NavBar.propTypes = {
    classes: PropTypes.object.isRequired,
};

export default withStyles(styles)(NavBar);

这就是我使用它的地方:

class App extends Component{

  constructor(props){
    super(props);

    this.state = {
      isAuthenticated: false,
      isAuthenticating: true
    };
  }

  // Functions

  render(){

    const childProps = {
      isAuthenticated: this.state.isAuthenticated,
      userHasAuthenticated: this.userHasAuthenticated
    };

    return (
      !this.state.isAuthenticating &&
      <MuiThemeProvider theme={theme}>
        <div className = "App">
          <NavBar props={childProps} />
          <Routes childProps={childProps} />
        </div>
      </MuiThemeProvider>
    );
  }
}

export default App;

现在,这将 props 视为“未定义”。老实说,我不知道从哪里开始添加第二个 props,因为我对 Node.js 和一般的 Web 开发仍然相当陌生。

最佳答案

而不是这样做:

<NavBar props={childProps} />

您可以选择传播 Prop :

/*
 * Assuming eg: const childProps = {isAuthenticated: true};
 */
<NavBar {...childProps} />

或者您可以像这样直接分配它们:

/*
 * Assuming eg: const isAuthenticated = true;
 */
<NavBar isAuthenticated={isAuthenticated} />

关于javascript - 如何将 props 传递给 Material-ui 风格的组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56643723/

相关文章:

node.js - 使用流程时导入 native Node 模块的正确方法是什么?

node.js - 如何获取 strip 订阅 current_period_end 作为日期

javascript - 不使用 anchor 标记或散列滚动到 ID

javascript - 上一篇状态不一致

javascript - webpack如何使用合并css文件?

javascript - jQuery datepicker 不更新 minDate

javascript - 在 react 服务器端渲染的应用程序中启用滚动

node.js - 为 AWS Lambda 和无服务器推荐什么本地 Node 版本

javascript - php 的动态名称属性

javascript - Fabric.js Canvas - 使一种对象始终位于另一种对象下方