You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React新手求助:实现输入框有内容时才显示添加按钮

Fixing Your React Form: Show Add Button Only When Input Has Content

Hey there! Let's get your form working the way you want it. I spotted a couple of small issues in your code that are keeping it from behaving correctly—let's break them down and fix them together.

First: The Button Visibility Condition Is Wrong

Right now, you're checking if(this.handleChange) to decide whether to show the button. But handleChange is always a valid function in your component, so this condition will always be true—that's why the button never hides. Instead, you need to check if the input has actual content (we'll use trim() to ignore just whitespace):

let button;
if(this.state.value.trim()) { // Checks if input has non-whitespace content
  button = <button type="submit">Add</button>;
}

Second: Your handleAdd Function Has a Logic Error

Your current handleAdd treats this.state.value like an array, but your initial state sets value as an empty string. This will cause weird behavior (like splitting the input string into individual characters). Instead, you should add a separate array to your state to store the items you've added, then push the input value into that array.

Here's the Full Corrected Code

class App extends Component {
  state = { 
    value: '',
    items: [] // New array to store added items
  };

  handleChange = (e) => {
    // No need for e.preventDefault() here—input onChange doesn't trigger a form submit
    this.setState({ value: e.currentTarget.value });
  };

  handleAdd = (e) => {
    e.preventDefault();
    // Add the current input value to the items array, then clear the input
    this.setState(prevState => ({
      items: [...prevState.items, prevState.value],
      value: ''
    }));
  };

  render() {
    let button;
    // Show button only if input has non-whitespace content
    if(this.state.value.trim()) {
      button = <button type="submit">Add</button>;
    }

    return (
      <div className="formulaire">
        <form onSubmit={this.handleAdd}>
          <label>
            <p>Name:</p>
            <input value={this.state.value} onChange={this.handleChange} />
          </label>
          {button}
        </form>
        {/* Optional: Display the added items to see the result */}
        <div className="added-items">
          <h3>Added Names:</h3>
          <ul>
            {this.state.items.map((item, index) => (
              <li key={index}>{item}</li>
            ))}
          </ul>
        </div>
      </div>
    );
  }
}

Key Changes Explained:

  • Updated State: Added an items array to keep track of all the names you've added, while value still manages the input field's content.
  • Fixed Button Condition: Now checks if this.state.value.trim() is truthy—meaning the input has actual text, not just spaces.
  • Corrected handleAdd: Uses the previous state to safely update the items array (best practice in React when updating state based on existing state), then clears the input field after submission.
  • Added Item Display: Included a section to show all added names so you can see the form working as expected.

内容的提问来源于stack exchange,提问作者user11953983

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:06:21