我有一个组件,我也想传递 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/