【发布时间】:2019-05-06 04:30:49
【问题描述】:
我有一个这样的无状态组件:
import React from 'react';
import PropTypes from 'prop-types';
const Panel = (props) => {
return(
<div
className={props.className}
onClick={props.onClick}>
<p>{props.firstChild}</p>
<p>{props.secondChild}</p>
<p>{props.thirdChild}</p>
</div>
)
}
Panel.propTypes = {
onClick: PropTypes.func.isRequired,
className:PropTypes.any.isRequired,
firstChild: PropTypes.string.isRequired,
secondChild: PropTypes.string.isRequired,
thirdChild: PropTypes.string.isRequired,
};
export default Panel
我的 Class 组件是这样的:
import React, { Component } from 'react';
import Panel from './panel'
class ImageGallery extends Component {
constructor(props){
super(props)
this.state = {
open: false,
}
}
toggleOpen = () => {
console.log('hi')
this.setState({
open: !this.state.open
})
}
render() {
return (
<div className="panels">
<Panel
firstChild="Hey"
secondChild="Let's"
thirdChild="Talk"
onClick={this.toggleOpen}
className={this.state.open ? "panel panel1 open open-active " : "panel panel1"}
/>
<Panel
firstChild="Hey"
secondChild="Give"
thirdChild="Me"
onClick={this.toggleOpen}
className={this.state.open ? "panel panel2 open open-active " : "panel panel2"}
/>
</div>
)
};
}
export default ImageGallery;
点击一个Panelcomponent 希望这个将open 和open-active 类添加到我的项目中。
目前一个项目上的 onClock 都在打开,但我希望两者分开处理。
我不确定如何以最简洁的方式使用状态和类。
感谢您的帮助
【问题讨论】: