我正在尝试创建一个组件,该组件检查道具的长度,将字符串切成薄片,如果超过一定数量的字符,则显示链接,然后在链接单击上显示/隐藏全长。我觉得我的安装尚无法实现所描述的功能,但是我在配置链接组件方面遇到了问题。我仍在学习React,并且不确定是否需要在TextExpandButton
语句中将链接包装在return()
中,或者它是否源于其他问题。
这是完整的错误:
Uncaught Error: TextExpandButton(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.
这是完整的代码:
import React from 'react';
//Annotation Card - Body
export default class Body extends React.Component {
constructor(){
super();
this.state = { showFullText: false, characterLimit: 5, expandButtonText: "Show More..." };
}
expandFullText(){
this.setState({
showFullText: true,
characterLimit: this.props.discovery.length,
expandButtonText: "Show Less"
});
}
render() {
//Annotation Card - Body - Text Expand Link
const TextExpandButton = props => {
<a href="#" onClick={this.expandFullText}>this.props.buttonText</a>
}
const partialText = this.props.discovery.slice(0, this.state.characterLimit);
var textExpandButton;
if(this.props.discovery.length > this.state.characterLimit) {
textExpandButton = <TextExpandButton buttonText={this.state.expandFullText} />;
} else {
return null;
}
return (
<div>
<p>{partialText}</p>
{textExpandButton}
</div>
)
}
}
答案 0 :(得分:1)
您弄乱了代码
第一件事TextExpandButton是一个功能组件,因此它应该在类组件之外,而不是在渲染内部
从主体组件中删除以下代码
const TextExpandButton = props => {
<a href="#" onClick={this.expandFullText}>this.props.buttonText</a>
}
将其放置在类外部组件
export const TextExpandButton = props => {
return <a href="#" onClick={props.buttonText}>show more...</a>
}
然后改变
textExpandButton = <TextExpandButton buttonText={this.state.expandFullText} />;
在您的身体组件中
textExpandButton = <TextExpandButton buttonText={this.expandFullText} />;
答案 1 :(得分:0)
您需要从功能组件中返回一些东西。
组件:
import React from 'react';
//Annotation Card - Body
export default class Body extends React.Component {
constructor(){
super();
this.state = { showFullText: false, characterLimit: 5, expandButtonText: "Show More..." };
}
expandFullText(){
this.setState({
showFullText: true,
characterLimit: this.props.discovery.length,
expandButtonText: "Show Less"
});
}
render() {
//Annotation Card - Body - Text Expand Link
const TextExpandButton = props => {
return <a href="#" onClick={this.expandFullText}>this.props.buttonText</a>
}
const partialText = this.props.discovery.slice(0, this.state.characterLimit);
var textExpandButton;
if(this.props.discovery.length > this.state.characterLimit) {
textExpandButton = <TextExpandButton buttonText={this.expandFullText} />;
} else {
return null;
}
return (
<div>
<p>{partialText}</p>
{textExpandButton}
</div>
)
}
}
或者您可以这样做:
const TextExpandButton = props => <a href="#" onClick={this.expandFullText}>this.props.buttonText</a>