我将 props 传递给可以是字符串或 SVG 的组件。我想根据类型有条件地渲染它。
这是我尝试过的:
const ProjectIcon = ({icon}) => { // icon can be an SVG or just a string string
console.log("string: "+icon);
console.log(typeof icon === "string"); // true for both string AND SVG
console.log(typeof icon !== "string"); // false for both string AND SVG
return (...) // return based on the type of props
}
我导入 SVG 文件或在远程父组件中设置字符串变量:
Parent.jsx
import svg from "./icon.svg";
import Parent from "./Parent.jsx";
const Parent = () => {
return (
<ProjectIcon icon={svg}>
)
}
我导入这个icon.svg
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="100%">
<circle cx="50" cy="50" r="50"/>
</svg>
这两种类型似乎都像字符串一样被解释。我如何区分 JavaScript/React 的区别?
最佳答案
如果您导入的 svg 作为字符串出现,您可以将其解析回对象并检查类型。
const icon1 = <svg...>...</svg>
const icon2 = 'some string'
JSON.parse(JSON.stringify(icon1)).type==='svg'// is true
JSON.parse(JSON.stringify(icon2)).type==='svg'// is false
否则 svg 只是一个对象,typeof icon
应相应地给出对象或字符串。还可以检查 svg 的长度应该是未定义
。查看下面的片段。字符串的圆形背景颜色为蓝色,svg 的圆形背景颜色为红色。
function Tile(){
const SVG = <svg viewBox="0 0 100 100" fill="grey">
<circle cx="50" cy="50" r="30" /></svg>
return <div>
<div className='tile'><Circle icon={SVG}/></div>
<div className='tile'><Circle icon='test'/></div>
</div>
}
function Circle({icon}){
return <div style={{background: icon.length?'blue':'red'}} className='circle'>{icon}</div>
}
ReactDOM.render(<Tile/>, document.getElementById('root'))
.tile{ position: relative; display: inline-block; margin-left: 10px; width: 100px; height: 100px; background: orange; }
.circle{ position: absolute; top: 25px; left: 25px; width: 50px; height: 50px; border-radius: 50%; line-height: 50px; text-align: center; color: white; font-weight: bold; font-size: 20px; }
<div id='root'></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.6/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.6/umd/react-dom.production.min.js"></script>
关于javascript - 检查 props 是否包含字符串或 SVG,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60308954/