寻找一些关于我可以做些什么来实现这一目标的提示。基本上,我有一个输入,附近有按钮,可以快速输入。单击按钮时,需要模拟将值粘贴到用户光标所在的文本字段中。此外,如果有突出显示的内容,则应将其替换为输入的文本。
我现在正在使用 redux-form 的更改操作来更新值,这适用于添加到末尾 - 但没有给出我正在寻找的效果。
最佳答案
您在这里想要实现的目标与浏览器的默认行为背道而驰。单击按钮将导致输入以及光标位置失去焦点状态。当然,您可以通过重载组件状态来解决这个问题,但是当您添加更多输入和逻辑时,它可能会变得难以管理。
为了便于讨论,我在这里发布了一个可能的解决方案,除非有充分的理由,否则我不会将其交付生产。
您需要将输入值存储在状态中,这就是 redux-form是的,我在示例中使用普通组件状态。每当您的焦点从输入移动到按钮(模糊事件)时,您都会获得输入 selectionStart
和 selectionEnd
并进行状态更新,将原始输入值中它们之间的内容替换为您的自定义值。
就像我说的,添加多个输入会使事情变得复杂,因为您需要将每个输入引用绑定(bind)到一个状态键。
class MyForm extends React.Component {
constructor() {
super();
this.state = {
inputValue: ''
}
}
render() {
return <form>
<input
value={this.state.inputValue}
ref={e => this.input = e}
onBlur={this.onBlurInput}
onChange={this.onInputChange}
/>
<br />
<button
ref={e => this.button = e}
type="button"
onClick={this.onAppend}
>
Append to cursor
</button>
</form>;
}
onBlurInput = (e) => {
// `e.target` is the input being blurred here
const stringToInsert = 'Hello World';
const {inputValue} = this.state;
const {selectionStart, selectionEnd} = e.target;
// We've clicked the button and the input has become blurred
if (e.relatedTarget === this.button) {
const newInputValue = inputValue.substring(0, selectionStart) +
stringToInsert +
inputValue.substring(selectionEnd);
this.setState({
inputValue: newInputValue
})
}
}
onAppend = (e) => {
// Re-focus the input
this.input.focus();
}
onInputChange = (e) => {
this.setState({
inputValue: e.target.value
});
}
}
ReactDOM.render(<MyForm />, document.getElementById('root'));
<link href="https://cdnjs.cloudflare.com/ajax/libs/normalize/3.0.2/normalize.min.css" rel="stylesheet" type="text/css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
关于reactjs - 使用 React (2/redux-form) 模拟将值粘贴到字段中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45041250/