问答题652/1620react是否支持给标签设置自定义的属性,比如给video标签设置webkit-playsinline?

难度:
2022-08-07 创建

参考答案:

如果你在react中这么样写:

1// Your code: 2<div mycustomattribute="something" />

在react 15中将被渲染成:

1// React 15 output: 2<div />

在react 16及之后的版本中将被渲染成:

1// React 16 output: 2<div mycustomattribute="something" />

但这个会有限制,如果自定义的属性不是 string, number 或者 object,该属性依然会被忽略。

所以目前可以这样添加 webkit-playsinline 属性:

1<video width="750" height="500" controls webkit-playsinline="true"> 2 <source src="https://media.w3.org/2010/05/sintel/trailer.mp4" type="video/mp4"/> 3</video>

另外,还可以通过 setAttribute 进行设置,比如:

1import * as React from 'react'; 2import { Component } from 'react'; 3 4export class VideoComponent extends Component { 5 videoContainer: HTMLDivElement; 6 componentDidMount() { 7 const video = document.createElement('video'); 8 video.autoplay = true; 9 video.loop = true; 10 video.muted = true; // fixes autoplay in chrome 11 video.setAttribute('playsinline', 'true'); // fixes autoplay in webkit (ie. mobile safari) 12 13 const source = document.createElement('source'); 14 source.src = '/path/to/your/video.mp4'; 15 source.type = 'video/mp4'; 16 video.appendChild(source); 17 18 this.videoContainer.appendChild(video); 19 } 20 render() { 21 return ( 22 <div ref={(ref) => { this.videoContainer = ref; }} /> 23 ); 24 } 25} 26

最近更新时间:2024-08-10

赞赏支持

题库维护不易,您的支持就是我们最大的动力!