这是我现在的代码:
class QuoteDisplay extends React.Component {
tweetOut() {
const quote = this.props.quote;
const author = this.props.author;
window.open("https://twitter.com/intent/tweet?text=" + quote + ' - ' + author);
}
render(){
const quote = this.props.quote;
const author = this.props.author;
const handleGetQuote = this.props.handleGetQuote;
return (
<div className='quoteDisplay'>
<span className='quote'>{quote}</span>
<span className='author'>-{author}</span>
<br/>
<button
className='btn btn-primary newQuote'
onClick={handleGetQuote}>
New Quote
</button>
<button
className='btn btn-primary tweet'
onClick={this.tweetOut.bind(this)}
>
Tweet Out
</button>
</div>
)
}
}
正如您所看到的,我重复了两次代码片段 - 一次是在tweetOut()中,一次是在render()中:
const quote = this.props.quote;
const author = this.props.author;
有没有办法重构这段代码,所以我不必重复自己?我尝试在类组件的开头声明它。甚至为它创建一个构造函数,但这些方法似乎不起作用。
答案 0 :(得分:0)
这个值在函数和渲染中都是必需的,所以我建议你使用ES6解构并执行:
tweetOut() {
const { quote, author } = this.props;
window.open("https://twitter.com/intent/tweet?text=" + quote + ' - ' + author);
}
与render()中的代码相同:
const {quote, author, handleGetQuote } = this.props;