gpt4 book ai didi

javascript - 在 React.js 中实现阅读更多链接

转载 作者:可可西里 更新时间:2023-11-01 13:07:50 26 4
gpt4 key购买 nike

我正在尝试实现一个 Read More 链接,该链接会展开以显示单击后显示更多文本。我正在尝试以 React 的方式做到这一点。

<!--html-->
<div class="initialText">
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
<a>
Read More
</a>
</div>

<div class="fullText">
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</div>

/* JavaScript */
/* @jsx DOM */
var component = React.createClass({

getInitialState: function() {
return {
expanded: false
};
},

expandedText: function() {
this.setState({
expanded: true
});
},

render: function() {
return (
<div>

</div>
);
}

});

我是 React 的新手。我不确定如何处理渲染方法中的所有内容。我如何在纯 React 中实现此功能?

最佳答案

所以基本上你想根据状态属性'expanded'显示一个额外的div。

您可以有条件地创建组件。如果你不想要一个组件,你可以只返回 null。我只需要一个小方法,例如:

var component = React.createClass({
getInitialState: function() {
return {
expanded: false
};
},

expandedText: function() {
this.setState({
expanded: true
});
},

getMoreTextDiv: function() {
if (this.state.expanded) {
return <div> My extended content </div>;
} else {
return null;
}
}
});

你的渲染函数应该变成:

render: function() {
var expandedDiv = this.getMoreTextDiv();
return (
<div>
<a onClick={this.expandedText}>Read more</a>
{ expandedDiv }
</div>
);
}

每次调用 setState() 时,您都会使用新状态触发 render()

如果 expanded 为 false,您将返回 null 作为组件,这基本上意味着什么都没有。所以什么也不会显示。

当您点击您的链接时,它会更新您的状态和扩展值,因此您将返回一个 div 作为组件并显示。

我认为阅读 this 是一个好的开始.这是一篇非常棒的文章,解释了渲染的基本工作原理,以及与状态的链接。

你还应该确保你理解这种小例子http://jsfiddle.net/3d1jzhh2/1/查看状态和渲染如何相互关联。

关于javascript - 在 React.js 中实现阅读更多链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29996048/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com