想使用reactjs显示更多功能

问题描述 投票:0回答:1

最初,如果字符长度超过20,则将显示显示更多按钮,并且在单击显示更多按钮时将显示所有文本。为此,我正在使用对象数组。我无法检测到单击setState的特定对象。

    class App extends React.Component {
      state = {
        posts: [],
        maxLength: 20
      }

      componentDidMount() {
        fetch('https://jsonplaceholder.typicode.com/posts')
          .then(response => response.json())
          .then(json => this.setState({
            posts: json
          }))
      }

      showMore(item) {
        if (item.id == this.state.posts[id - 1].id) {
          this.setState({
            maxLength: item.body.length
        })
       }
      }

      render() {

        return (
          <div>
            {
              this.state.posts.map((item) => {
                return (
                  <div style={{ padding: '10px', border: '1px solid', marginBottom: '10px' }} key={item.id}>
                    <p>{item.id}</p>
                    <p>{item.body.length > this.state.maxLength ? item.body.slice(0, this.state.maxLength) : item.body }</p>
                    {
                      item.body.length > 20 ?
                        <button onClick={this.showMore(item)}>ShowMore</button>
                        : null
                    }
                  </div>
                )
              })
            }
          </div>
        )
      }
    }
javascript reactjs
1个回答
0
投票

更改此代码onClick={() => this.showMore(item)}

     {item.body.length > 20 ? (
                <button onClick={() => this.showMore(item)}>ShowMore</button>
     ) : null}

并更改为箭头功能。

 showMore = item => {
    if (item.id === this.state.posts[item.id - 1].id) {
      this.setState({
        maxLength: item.body.length
      });
    }
  };

您的代码https://codesandbox.io/s/friendly-chebyshev-r69to的实时演示

© www.soinside.com 2019 - 2024. All rights reserved.