如何有条件地呈现占位符,该占位符返回字符,而不是字符串值本身?
为什么第二个输入占位符被解释为特殊字符,而第一个则被解释为字符串
class App extends React.Component{
render(){
const {mode} = this.props;
return(
<div>
<div><input type="password" placeholder={mode ?"pass":"●●●●"} /></div>
<input type="password" placeholder="●●●●"/>
</div>
)
}
}
ReactDOM.render(
<App mode={false}/>,
document.getElementById("react")
);
<div id="react"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
正如评论所说,我们可以直接使用该符号。
还有另一个程序化解决方案:DOMParser((
DOMParser接口提供了将字符串中的XML或HTML源代码解析为DOM文档的能力。
const yourText = `●`
const parser = new DOMParser();
const text = parser.parseFromString(yourText, "text/html").body.textContent;
placeholder={mode && text}
点击此处查看更多示例:
const App = () => {
const InputMode0 = () => {
return (
<div>
<input type="password" placeholder="●●●●" />
</div>
);
};
const InputMode1 = ({ mode }) => {
const parser = new DOMParser();
const text = parser.parseFromString(
`●●●●`,
"text/html"
).body.textContent;
return (
<div>
<input
type="password"
{...(mode
? { placeholder: text }
: { placeholder: `●●●●` })}
/>
</div>
);
};
const InputMode2 = ({ mode }) => {
const parser = new DOMParser();
const text = parser.parseFromString(
`●●●●`,
"text/html"
).body.textContent;
return (
<div>
<input
type="password"
placeholder={mode ? text : `●●●●`}
/>
</div>
);
};
return (
<div className="App">
<InputMode0 />
<InputMode1 mode={false} />
<InputMode1 mode={true} />
<InputMode2 mode={false} />
<InputMode2 mode={true} />
</div>
);
}
ReactDOM.render(<App />, document.getElementById("root"));
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.12.0/umd/react-dom.production.min.js"></script>