![](/img/trans.png)
[英]How to redirect to a class component from another class component in reactjs
[英]ReactJS - change class of component from another component?
对于React来说,它是一个非常新的东西,它来自jQuery背景,我想做的第一件事就是切换类。
我了解如何在相同的react组件中像这样切换类:
class ButtonParent extends React.Component {
constructor(props) {
super(props)
this.state = {
condition: false
}
this.handleClick = this.handleClick.bind(this)
}
handleClick() {
this.setState({
condition: !this.state.condition
})
}
render() {
return (
<ButtonChild
className={ this.state.condition ? "button toggled" : "button" }
toggleClassName={ this.handleClick }
>
Click me if you dare!
</ButtonChild>
)
}
}
class ButtonChild extends React.Component {
render() {
return (
<div
className={ this.props.className }
onClick={ this.props.toggleClassName }
>
{ this.props.children }
</div>
)
}
}
ReactDOM.render(<ButtonParent />, document.getElementById('app'))
但是,如果我要使用一个单独的组件来切换该组件的类怎么办? 在React中没有简单的方法可以做到这一点吗?
谢谢!
只需在ButtonParent.js文件附近创建一个ButtonChild.js文件,然后导出您的组件
export default class ButtonChild extends React.Component {
render() {
return (
<div
className={ this.props.className }
onClick={ this.props.toggleClassName }
>
{ this.props.children }
</div>
)
}
}
像这样将其导入您的ButtonParent.js文件中
import ButtonChild from './ButtonParent.js'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.