React dangerouslySetInnerHTML 渲染 iframe youtube 嵌入自 props

React dangerouslySetInnerHTML to render an iframe youtube embed from props?

本文关键字:props youtube dangerouslySetInnerHTML 渲染 iframe React      更新时间:2023-09-26

>有人知道如何在 React 中将这个 prop 属性获取到 stringToHTML 吗?提前感谢!

var Video = React.createClass({
getDefaultProps: function getDefaultProps() {
        return propsObj;
},
createMarkup: function() { 
    return {__html: {this.props.video}}; 
},
  render: function() {
    return (
      <div className="video-container no-controls" id="player" dangerouslySetInnerHTML={createMarkup()} />
    );
  }
});

React 中的 HTML 注入具有如此繁琐的 API 是有原因的:强烈建议不要使用它。

目前

还不清楚为什么你想使用HTML注入来做像YouTube视频iframe这样简单的事情。它的标记是完全可以预测的。

我强烈建议您用JSX重写它。这是我在最近的一个项目中使用的YouTube组件的代码。

const YouTubeVideo = ({ id }) => (
    <div className="youtube-wrapper">
        <div className="youtube">
            <iframe
                className="youtube-frame"
                src={`https://www.youtube.com/embed/${id}?autoplay=1`}
                allowFullScreen
            />
        </div>
    </div>
);