Last active
August 22, 2019 13:03
-
-
Save hacker0limbo/eb8bd3c685b2282e6ed6555e62a4f8e9 to your computer and use it in GitHub Desktop.
使用 useState 实现 readmore 效果
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import React, { useState } from 'react' | |
| import ReactDOM from 'react-dom' | |
| const text = 'To see the answers, we need to take a step back. The goal of this article isn’t to give you a list of bullet point recipes. It’s to help you truly “grok” useEffect. There won’t be much to learn. In fact, we’ll spend most of our time unlearning.' | |
| const RevealText = props => { | |
| const { text, maxLength } = props | |
| const [hidden, setHidden] = useState(true) | |
| if (text.length <= maxLength) { | |
| return ( | |
| <span>{text}</span> | |
| ) | |
| } | |
| return ( | |
| <span> | |
| {hidden ? text.substring(0, maxLength) : text} | |
| {hidden ? ( | |
| <a href="#" onClick={() => setHidden(false)}>...read more</a> | |
| ) : ( | |
| <a href="#" onClick={() => setHidden(true)}>read less</a> | |
| )} | |
| </span> | |
| ) | |
| } | |
| ReactDOM.render(<RevealText maxLength={32} text={text} />, document.querySelector('#root')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment