我检查了other questions还有docs但我无法让它发挥作用。我想将处理程序函数传递给其 props 中的子组件,以在主题之间进行更改。
我在父组件中定义了一个状态以及设置新状态的处理程序。我尝试过使用和不使用参数。
这是父级
class MyApp extends App {
constructor(props) {
super(props);
this.state = {
colorScheme: "light"
};
this.handleColorScheme = this.handleColorScheme.bind(this);
}
handleColorScheme = scheme => {
this.setState({ colorScheme: scheme });
};
render() {
const { Component, pageProps } = this.props;
const props = {
...pageProps,
schemeHandler: this.handleColorScheme
};
return (
<Container>
<ThemeProvider
theme={this.state.colorScheme === "light" ? theme : themeDark}
>
<Component {...props} />
</ThemeProvider>
</Container>
);
}
}
export default MyApp;
这是子组件
export default function Layout(props) {
const [theme, setTheme] = useState({
palette: {
type: "light"
}
});
const toggleDarkTheme = () => {
let newPaletteType = theme.palette.type === "light" ? "dark" : "light";
props.schemeHandler(newPaletteType);
};
return (
<div>
<CssBaseline />
<div className={classes.root}>
<AppBar
position="absolute"
color={"default"}
className={classes.appBar}
>
<Toolbar>
<IconButton onClick={toggleDarkTheme}>
<Dark />
</IconButton>
</Toolbar>
</AppBar>
<main className={classes.content}>
{props.children}
</main>
</div>
</div>
);
}
当我单击按钮时,它说 toggleDarkTheme
不是一个函数。使用开发工具进行调试,我发现我从未到达父函数。这个函数如何在 props 中传递?
最佳答案
你不应该在父级和子级中都使用状态,这会让你的逻辑变得复杂。您可以将状态放置在父级中,并将修饰符函数作为 prop 传递给子级(子级成为dumb组件)。
无需绑定(bind)修饰函数。
父组件可以成为函数而不是类。
示例: https://codesandbox.io/embed/passing-react-func-as-props-kf8lr
关于javascript - 在 props 中将函数传递给 React 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57507334/