javascript - 在输入值更改时更新其他组件 React
问题描述
我正在学习 React,我正在尝试根据输入值更新一个组件。我已经使用 html 和 vanilla JavaScript 完成了这项工作,并且可以正常工作。我正在尝试使用 React 实现相同的功能,但我遇到了一些挑战。
这是我在香草 javascript 中的代码:
index.html
<!DOCTYPE html>
<html lang="en">
<body>
<div>
<div>
<div>
<h2>Press button when you are ready to play</h2>
<input type="text" placeholder="Start typing..." id="word-input" autofocus>
</div>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
script.js
const wordInput = document.querySelector('#word-input');
const currentWord = document.querySelector('#current-word');
const words = [
'rock', 'paper', 'scissors', 'play'
];
displayWord(words)
wordInput.addEventListener('input', matchWords);
function displayWord(word) {
const Index = Math.floor(Math.random() * word.length);
currentWord.textContent = word[Index];
};
// match words
function matchWords() {
if(wordInput.value === currentWord.innerHTML) {
displayWord(words);
wordInput.value = '';
};
};
到目前为止,这是我在 React 中尝试过的:
import React, { Component, createRef } from 'react'
export class About extends Component {
state = {
words: [
'rock', 'paper', 'scissors', 'play'
],
current_input: 'Start...',
current_word: 'break'
}
inputRef = createRef();
displayWord = (word) => {
const Index = Math.floor(Math.random() * word.length);
let rword = word[Index];
this.setState({
current_word: rword
})
};
matchWords = (e) => {
this.setState({
current_input: e.target.value
})
if(this.state.current_input === this.state.current_word) {
this.displayWord(this.state.words);
this.setState({
current_input: ''
})
this.inputRef.current.focus();
};
};
render() {
return (
<div>
<div>
<div>
<h2 id="current-word">{this.state.current_word}</h2>
<input ref={this.inputRef}
placeholder='start ..' onChange={this.matchWords} type="text" id="word-input" autoFocus />
</div>
</div>
</div>
)
}
}
export default About
它似乎工作。但是,问题是在我输入单词后它不会更新 - 我必须在看到新单词出现之前尝试删除输入框的内容。此外,它不会自动清除内容并自动聚焦在输入框上,以便我输入新单词。我想知道我缺少什么以及就最佳实践而言,这是使用 React 执行此类操作的最佳或“正确”方式。谢谢!
解决方案
我认为,您应该在函数内部更改代码,matchWords
如下所示:
matchWords = (e) => {
if (e.target.value === this.state.current_word) {
this.displayWord(this.state.words);
this.setState({
current_input: ""
});
this.inputRef.current.focus();
} else {
this.setState({
current_input: e.target.value
});
}
};
它不会像您期望的那样立即运行,因为在比较当前输入是旧值setState
时异步运行。if (this.state.current_input === this.state.current_word)
就像您键入break
比较时一样if ('brea' === 'break')
推荐阅读
- python - 我对这段代码的分析是否正确,为什么会这样写?
- pyspark - Databricks-connect with Python + Scala UDF in JAR file not working local
- excel - 阻止单元格而不阻止列表
- android - SwipeRefreshLayout 替换 Fragments 后消失
- amazon-web-services - 如何在 CloudFormation 中使用 EBS 卷创建 EC2 实例?
- r - 在R中的data.frames列表中提取一组多个变量
- java - 如何在单击按钮时从 ArrayList 和 ArrayAdapter 中删除所选项目?
- python - 如何给 Python 函数一个函数作为参数,但它还不能调用?
- javascript - 单击进度条并了解视频之前(和之后)的计时器
- c# - 为什么 RichTextBox 隐式添加换行符?