当用户输入空格时,为什么会创建水平线?

时间:2017-12-20 11:48:23

标签: javascript css reactjs

这是我的代码。当我尝试运行它时,对于空白空间作为输入,它会创建一条水平线。

import React, { Component } from 'react';
export default class App extends Component {
constructor(props) {
    super(props);
    this.state = { items: [], text: '' };
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
} 

render() {
    return (
      <div>
        <form onSubmit  = {this.handleSubmit}>
          <input 
            onChange={this.handleChange}
            value={this.state.text />
        </form>
        <div>
          <TodoList items={this.state.items} />
        </div>
      </div>
    );
}

handleChange(e) {
    this.setState({ text: e.target.value });
}

handleSubmit(e) {
    e.preventDefault();
    if (!this.state.text.length) {
        return;
    }
    const newItem = {
       text: this.state.text,

    };
    this.setState(prevState => ({
      items: prevState.items.concat(newItem),
      text: ''
    }));
}
}

class TodoList extends React.Component {
    render() {
       return (

         <div>

          {this.props.items.map(item => (
           <h3 key={item.id}>{item.text}</h3>
          ))}

         </div>  
       );
    }

}

1 个答案:

答案 0 :(得分:1)

即使以空格作为输入,您的代码也会始终附加<h3>元素。

你看到一条水平线可能是因为应用了CSS样式 h3

您可以做什么阻止用户插入空白数据。一种方法是在进行长度检查之前trim()用户的输入:

// In handleSubmit()
if (!this.state.text.trim().length) {
  return;
}

现在只输入空格将变为0长度,因此更早退出handleSubmit()

import React, { Component } from 'react'

class TodoList extends React.Component {
  render() {
    return (
      <div>
        { this.props.items.map(item => <h3 key={ item.id }>{ item.text }</h3>) }
      </div>
    );
  }
}

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = { items: [], text: '' };
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(e) {
    this.setState({ text: e.target.value });
  }

  handleSubmit(e) {
    e.preventDefault();
    if (!this.state.text.trim().length) {
      return;
    }
    const newItem = {
      text: this.state.text,

    };
    this.setState(prevState => ({
      items: prevState.items.concat(newItem),
      text: ''
    }));
  }

  render() {
    return (
      <div>
        <form onSubmit={ this.handleSubmit }>
          <input onChange={ this.handleChange } value={ this.state.text }/>
        </form>
        <div>
          <TodoList items={ this.state.items } />
        </div>
      </div>
    )
  }
}