我很难更改以下代码以合并反应挂钩。
我已尝试遵循多个教程以及阅读有关堆栈溢出的文章。
class App extends Component {
constructor() {
super();
this.state = {
isFlipped: false
};
this.handleClick = this.handleClick.bind(this);
}
handleClick(e) {
e.preventDefault();
this.setState(prevState => ({ isFlipped: !prevState.isFlipped }));
}
render() {
return (
<div>
<ReactCardFlip isFlipped={this.state.isFlipped} flipDirection="horizontal">
<BusinessCard key="front">
This is the front of the card.
<button onClick={this.handleClick}>Click to flip</button>
</BusinessCard>
<BusinessCardBack key="back">
This is the back of the card.
<button onClick={this.handleClick}>Click to flip</button>
</BusinessCardBack>
</ReactCardFlip>
</div>
);
}
}
我希望将其转换为包含React-Hooks
答案 0 :(得分:3)
要将隐身组件类转换为隐身组件功能,您必须要做
function App() {
const [isFlipped, setFlipped] = useState(false);
const handleClick = () => {
setFlipped(prevState => ({ isFlipped: !prevState.isFlipped }));
};
return (
<React.Fragment>
<ReactCardFlip isFlipped={isFlipped} flipDirection="horizontal">
<BusinessCard key="front">
This is the front of the card.
<button onClick={handleClick}>Click to flip</button>
</BusinessCard>
<BusinessCardBack key="back">
This is the back of the card.
<button onClick={handleClick}>Click to flip</button>
</BusinessCardBack>
</ReactCardFlip>
</React.Fragment>
);
}
更新:
不需要preventDefault
在更新new state
时应在setState中使用回调模式,该值取决于previous state