首页 > 解决方案 > 通过 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>
               );
        };

标签: javascriptcssreactjsreact-bootstrap

解决方案


导致重新渲染应该有一个状态变化,但每次你重新渲染你设置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>)
 }






推荐阅读