我有一个包含输入的App组件。每次我输入输入时,输入的值都会更新,并且消息组件会根据输入的长度打印不同的消息。同时,名为Character的第三个组件将字符串的每个字母单独打印到屏幕上。期望的行为是,当我单击其中一个字母时,它会从字符串中删除,新字符串会显示在屏幕上,并且输入也会使用新字符串进行更新。
我使用了一些 console.logs 进行调试,一切似乎都按预期进行,直到我尝试更新状态的最后一步,但由于某种原因,它没有得到更新。
class App extends React.Component {
constructor(props) {
super(props);
this.state = { text: "" };
}
render() {
const handleUpdateText = event => {
this.setState({
text: event.target.value
});
};
const inputLength = this.state.text.length;
const toArray = this.state.text.split("");
const handleDeleteLetter = index => {
toArray.splice(index, 1);
console.log(toArray);
const updatedArray = toArray.join("");
console.log(updatedArray);
this.setState({ text: updatedArray });
console.log(this.state.text);
};
return (
<>
<input type="text" onChange={handleUpdateText} />
<Message inputLength={inputLength} />
{toArray.map((letter, index) => (
<Character
key={index}
theLetter={letter}
deleteLetter={() => handleDeleteLetter(index)}
/>
))}
</>
);
}
}
class Message extends React.Component {
render() {
const { inputLength } = this.props;
let codeToPrint = "The text is long enough!";
if (inputLength <= 5) {
codeToPrint = "The text is not long enough!";
}
return <p>{codeToPrint}</p>;
}
}
class Character extends React.Component {
render() {
const { theLetter, deleteLetter } = this.props;
return (
<div
style={{
display: "inline-block",
padding: "16px",
textAlign: "center",
margin: "16px",
backgroundColor: "tomato"
}}
onClick={deleteLetter}
>
{theLetter}
</div>
);
}
}
完整的代码在这里:
https://codesandbox.io/s/react-the-complete-guide-assignment-2-list-conditionals-e6ty6?file=/src/App.js:51-1007
我真的不明白我做错了什么,我觉得与生命周期方法有某种关系。任何答案都会有所帮助。谢谢你。
ibeautiful
相关分类