在样式组件内部使用 Textarea 可以通过在 ReactJS 中重置光标位置使其向后写入

Using Textarea inside of styled components makes it write backwards by resetting position of cursor in ReactJS

我正在使用 react-textarea-autosizeTextareastyled componentsstyled。我正在 class 中编写一个 renderForm 函数,它呈现一个包含 StyledTextarea 的表单。经过分析,我发现使用Styled,每次写一个字符,光标的位置都会重新设置在开头,从而使它向后写。 我只用了一个简单的 <input>,一个简单的 <Textarea> 就检查过了,它们都正常工作。就在我添加样式组件时,它的行为就像这样。代码片段如下:

class ActionButton extends Component {
    renderForm() {
        const StyledTextarea = 
            styled(Textarea)`
            resize: none;
            width: 100%;
            overflow: hidden;
            outline: none;
            border: none;
          `; 

        return (
            <StyledTextarea
            autoFocus
            onBlur={this.closeForm}
            value={this.state.text}
            onChange={this.handleInputChange}
          />
        );
    }

    render() {
        return renderForm();
    }
}

这是我在 Whosebug 中的第一个 post。如有错误请见谅

我发现问题出在 StyledTextarea 的声明上。如果它在 class 之外声明,它工作正常。我不确定为什么。所以代码片段应该是这样的:

const StyledTextarea = 
    styled(Textarea)`
    resize: none;
    width: 100%;
    overflow: hidden;
    outline: none;
    border: none;
  `; 

class ActionButton extends Component {
    renderForm() {
        return (
            <StyledTextarea
            autoFocus
            onBlur={this.closeForm}
            value={this.state.text}
            onChange={this.handleInputChange}
          />
        );
    }

    render() {
        return renderForm();
    }
}

当然,如果class/states/props里面有依赖,那你就得做一个函数,把依赖作为参数传进去。