我有一個(gè)word最初設(shè)置為visitor. 該頁(yè)面有一個(gè) H1,上面寫(xiě)著"Hello, {this.state.word}"。頁(yè)面上有一個(gè)輸入,將 的狀態(tài)更改word為輸入的值。我想要發(fā)生的是,當(dāng)用戶(hù)更改Word使用輸入的狀態(tài)時(shí),能夠?qū)顟B(tài)設(shè)置回它的原始單詞,visitor只需按退格鍵直到頁(yè)面輸入為空。我嘗試在onChange()函數(shù)內(nèi)部使用條件邏輯來(lái)說(shuō)明如果word狀態(tài)等于空字符串,則將狀態(tài)設(shè)置word為visitor。由于某種我無(wú)法弄清楚的原因,這不起作用。import React, {Component} from 'react';import "./Visitor.css";class Visitor extends Component{ constructor(props){ super(props); this.state={ word: 'visitor' }; this.handleChange = this.handleChange.bind(this); } handleChange(e){ if(this.state.word === ''){ this.setState({ word: 'vis' }); } this.setState({ [e.target.name]: e.target.value }); } render(){ return( <div className="Visitor"> <h1>Hello, {this.state.word}</h1> <input type="text" onChange={this.handleChange} name="word" placeholder="Type your name here"/> <button>Clear</button> </div> ) }}export default Visitor;我的 try 和 failed if 語(yǔ)句沒(méi)有錯(cuò)誤消息,只是沒(méi)有正確的結(jié)果。結(jié)果應(yīng)該是在任何時(shí)候頁(yè)面上的輸入都是空的,“word”的狀態(tài)應(yīng)該是“visitor”。
在 React.js 中設(shè)置組件狀態(tài)時(shí)遇到問(wèn)題
拉風(fēng)的咖菲貓
2021-09-04 21:11:26