[英]React: how to set `dangerouslySetInnerHTML` from component's state?
I'm new to React and am working on an already-existing component that seems a bit old.我是 React 的新手,正在处理一个看起来有点旧的已经存在的组件。
I have a label element I want to set dynamically, depending on state. To this affect I have:我有一个 label 元素,我想根据 state 动态设置。为此,我有:
export default class Address extends React.Component {
// Props and other handlers
componentTitle() {
if (this.state.isPostal) {
return this.state.labels.PostalAddressLabel
}
else {
return this.state.labels.StreetAddressLabel
}
};
render() {
return (
<div className="block">
<div className="grid-x">
<div className="input-field cell">
<label
dangerouslySetInnerHTML={{ __html: componentTitle() }}
/>
// Other elements
}
}
However, this does not work.但是,这不起作用。 I get the error我得到错误
Uncaught ReferenceError: componentTitle is not defined未捕获的 ReferenceError:未定义 componentTitle
I've tried various combination of this including我尝试了各种组合,包括
Using a var const compTitle = componentTitle() {
使用 var const compTitle = componentTitle() {
placing the function within the render() function将 function 放在 render() function 中
And removing the function altogether and putting the if/else condition in the render() function, eg:并完全删除 function 并将 if/else 条件放入 render() function,例如:
if (this.state.isPostal) { const compTitle = this.state.labels.PostalAddressLabel } else { const compTitle = this.state.labels.StreetAddressLabel } return ( <div className="block"> <div className="grid-x"> <div className="input-field cell"> <label dangerouslySetInnerHTML={{ __html: compTitle }}
But I just can't get it to work.但我就是无法让它工作。
Could anyone point me in the right direction?谁能指出我正确的方向?
In this code:在这段代码中:
if (this.state.isPostal) {
const compTitle = this.state.labels.PostalAddressLabel
}
else {
const compTitle = this.state.labels.StreetAddressLabel
}
You the variable compTitle
only lives within the scope it's defined - which is between the curly braces.您的变量compTitle
仅存在于它定义的 scope 中 - 它位于花括号之间。 So, after the if
statement, that variable no longer exists.因此,在if
语句之后,该变量不再存在。
I suspect you want something like this:我怀疑你想要这样的东西:
const compTitle = this.state.isPostal
? this.state.labels.PostalAddressLabel
: this.state.labels.StreetAddressLabel
return (
<div className="block">
<div className="grid-x">
<div className="input-field cell">
<label>{compTitle}</label>
Easiest way to do this is the using ternary operator.最简单的方法是使用三元运算符。
export default class Address extends React.Component {
// Props and other handlers
render() {
const { isPostal, labels } = this.state;
const compTitle = isPostal ? labels.PostalAddressLabel : labels.StreetAddressLabel;
return (
<div className="block">
<div className="grid-x">
<div className="input-field cell">
<label
dangerouslySetInnerHTML={{ __html: compTitle }}
/>
// Other elements
)
}
}
use this keyword this.componentTitle()使用这个关键字 this.componentTitle()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.