我有一个简单的组件:
class News extends Component {
state = {
isSimple: this.props.isSimple
}
render() {
return (
<div>
<div className="extended">extended</div>
simple text
</div>
);
}
}
export default News;
我只想显示扩展显示或简单显示,所以我这样做:
class News extends Component {
state = {
isSimple: this.props.isSimple
}
render() {
var text;
if (this.state.isSimple) {
text = "simple <br /> text";
} else {
text = <div className="extended">extended</div>
}
return (
{text}
);
}
}
但是如果state isSimple = true,那么这会告诉我:
simple <br /> text
代替:
simple
text
此外,它不是很清晰。我可以在render方法的中间设置一个if条件吗?
答案 0 :(得分:2)
为什么需要保存文本并返回?而是返回jsx语句,而不是使用if语句,而是使用运算符。像这样:
class News extends Component {
state = {
isSimple: this.props.isSimple
}
render() {
const { isSimple } = this.state;
return (
{ isSimple ? <div>simple <br /> text</div>
: <div className="extended">extended</div>
}
);
}
}
答案 1 :(得分:1)
您可以使用"Jothijohnsamy"
将字符串包装在对象中,然后使用dangerouslySetInnerHTML
道具使用它:
{__html: 'your string here..'}
Fragments doesn't support dangerouslySetInnerHTML,所以我不得不在那里使用render() {
var text;
if (this.state.isSimple) {
text = <div dangerouslySetInnerHTML={{ __html: "simple <br /> text" }} />;
} else {
text = <div className="extended">extended</div>;
}
return text;
}
。
div
class News extends React.Component {
state = {
isSimple: this.props.isSimple
};
render() {
var text;
if (this.state.isSimple) {
text = <div dangerouslySetInnerHTML={{ __html: "simple <br /> text" }} />;
} else {
text = <div className="extended">extended</div>;
}
return text;
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<News isSimple={true} />, rootElement);
答案 2 :(得分:0)
我认为您缺少渲染方法的返回部分
render() {
var text;
if (this.state.isSimple) {
return <div>simple <br /> text</div>;
} else {
return <div className="extended">extended</div>;
}
}