javascript - 通过 onSubmit 在 React 中更改表单的 CSS 样式
问题描述
我正在使用 react-bootstrap 并试图让我的 Form.Control 在表单提交时更改其 CSS 样式。当提交发生时,我可以在我的控制台中看到formStyle
两者之间的变化,但是当我相信它会随着状态变化时,它不会用这些新样式重新渲染。
任何解释都会非常有帮助。
render() {
const lockedStyle = {
backgroundColor: "#26607d",
color: "#ffffff",
};
const unlockedStyle = {
backgroundColor: "#ffffff",
color: "#26607d",
};
let formStyle = lockedStyle;
const swap = event => {
event.preventDefault();
if (this.state.isLocked) {
formStyle = unlockedStyle; // Change to Unlocked
this.setState({ isLocked: false });
console.log(formStyle);
} else {
formStyle = lockedStyle; // Change to Locked
this.setState({ isLocked: true });
console.log(formStyle);
}
return (
<Form onSubmit={swap}>
<Form.Control
type="text"
placeholder="First Name"
style={formStyle}
>
<Button type="submit">Swap Styles</Button>
</Form>
);
};
解决方案
导致重新渲染应该有一个状态变化,但每次你重新渲染你设置formstyle为锁定风格let formStyle = lockedStyle;
尝试将 formStyle 移动到状态变量,然后将 this.state.formStyle 应用于样式,然后您可以删除 isLocked 并仅将 formStyle 保留为状态。只需在交换中的状态之间切换。
看看下面的例子。
但为了最佳实践,最好让 render 方法渲染和移动所有变量,因为一旦定义它们,您应该始终记住 render() 发生在每个状态更改 (setState) 上。
const unlockedStyle = .....
const lockedStyle = ....
export class ComponenetName extends React.Component {
constructor(){
this.state = {
formStyle:unlockedStyle
}
this.swap = this.swap.bind(this) //binding swap to this object for careful state changing , for future state changing from other components.... good practice
}
.....
swap = event => {
event.preventDefault()
this.setState((prevState) => {return {formStyle:(prevState.formStyle==lockedStyle? unlockedStyle : lockedStyle)}})```
}
.....
render() {
return (
<Form onSubmit={this.swap}>
<Form.Control
type="text"
placeholder="First Name"
style={this.state.formstyle}
>
<Button type="submit">Swap Styles</Button>
</Form>)
}
推荐阅读
- javascript - 如何使 SVG 在 codepen.io 等网站上响应?
- python - 程序跳过while-else
- j2ssh - 网络故障上的 J2SSH Maverick 行为
- c# - 将字符串数组列表复制到 excel 文件时的奇怪行为
- c++ - 如何在不使用 append 函数的情况下追加到 C++ 字符串?
- javascript - 为什么我的箭头函数错误为“不是函数”?
- mongodb - MongoDB 数据在 docker 容器上下移动之间不持久 [MacOSX]
- python - Python find.all [BeautifulSoup] 突然返回空
- c# - 从当前在 android 设备上播放的任何声音中获取数据?
- api - 在 SPFx 上的 MS Graph API 中转换文件返回未定义