使用 React-Hooks 将类组件转换为无状态组件



我很难更改下面的代码以合并反应钩子。

我尝试遵循多个教程以及阅读有关堆栈溢出的帖子。

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 组件类隐藏为 React 组件函数,您必须执行

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>
);
}

更新:

  • 预防默认不是必需的

  • 我们应该在 setState 中使用回调模式,同时更新new state哪个值依赖于previous state

相关内容

  • 没有找到相关文章

最新更新