最初,如果字符长度超过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>
)
}
}
更改此代码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
});
}
};