gpt4 book ai didi

reactjs - 用于切换 bool 值的无状态组件

转载 作者:行者123 更新时间:2023-12-03 14:14:05 25 4
gpt4 key购买 nike

将以下代码转换为无状态组件的正确方法是什么?

export default class About extends Component {

state = {
showKitten: false
}

handleToggleKitten = () => this.setState({ showKitten: !this.state.showKitten });

render() {
const { showKitten } = this.state;
const kitten = require('./kitten.jpg');
return (
<div className="container">
{showKitten && <div><img src={kitten} alt="kitchen" /></div>}
</div>
);
}
}

设法定义 Prop 等。以下代码用于记录消息。但是切换 bool 值的最佳方法是什么?

const handleToggleKitten = () => {
console.log('Hello from here');
**// How to toggle the value of boolean here?**
};

const About = (props) => {
const { showKitten } = props;
const kitten = require('./kitten.jpg');
return (
<div className="container">
{showKitten && <div><img src={kitten} alt="kitchen" /></div>}
</div>
);
};

About.defaultProps = {
showKitten: false
};

About.propTypes = {
showKitten: PropTypes.bool.isRequired
};

最佳答案

您应该有一个有状态组件来呈现无状态组件并向其传递和更新 Prop

class App extends React.Component {

state= {showKitten: false}
handleToggleKitten = () => {
this.setState((prevState, props) => ({
showKitten: !prevState.showKitten
}))
};

render() {
return (
<About showKitten={this.state.showKitten} handleToggleKitten={this.handleToggleKitten}/>
)

}
}
const About = (props) => {
const { showKitten } = props;

return (
<div className="container">
{showKitten && <div><img src={"http://addolo.com/wp-content/uploads/2016/12/kitten-pics-uncategorized-84-astonishing-photo-ideas-kittens-cattime-black-and-white-pictures-funny-with-captionskitten-cutekitten.jpg"} alt="kitchen" /></div>}
<button onClick={props.handleToggleKitten}>Toggle</button>
</div>
);
};


About.propTypes = {
showKitten: React.PropTypes.bool.isRequired
};

ReactDOM.render(<App/>, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>

关于reactjs - 用于切换 bool 值的无状态组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43870257/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com