gpt4 book ai didi

javascript - 将 React props 桥接至仅 JS setter

转载 作者:行者123 更新时间:2023-12-03 04:53:28 25 4
gpt4 key购买 nike

有时,人们可能想使用 prop 来设置只能通过 JS 设置的元素属性(因此无法通过 React 控制)。

一个示例(也是我的用例)是使用 paused 属性来定义视频是否应该播放(我的目标是分离视频的控件和可视化)。

这是我当前(简化)的实现:

class Video extends Component {
constructor() {
super();
this.videoElRef = this.videoElRef.bind(this);
}
// Called when the video element is mounted.
videoElRef(ref) {
this.videoEl = ref;
if (this.videoEl) {
this.updateVideoProp();
}
}
// Update JS only property from the Component props.
updateVideoProp() {
const { paused } = this.props;
const videoEl = this.videoEl;
// Pause or play the video depending on the `paused` property.
if (paused && !videoEl.paused) {
videoEl.pause();
} else if (!paused && videoEl.paused) {
videoEl.play();
}
}
render() {
if (this.videoEl) {
this.updateVideoProp();
}
return (
<video ref={this.videoElRef}>
{ this.props.children }
</video>
);
}
}

const Component = React.Component;

class Video extends Component {
constructor() {
super();
this.videoElRef = this.videoElRef.bind(this);
}
// Called when the video element is mounted.
videoElRef(ref) {
this.videoEl = ref;
if (this.videoEl) {
this.updateVideoProp();
}
}
// Update JS only property from the Component props.
updateVideoProp() {
const { paused } = this.props;
const videoEl = this.videoEl;
// Pause or play the video depending on the `paused` property.
if (paused && !videoEl.paused) {
videoEl.pause();
} else if (!paused && videoEl.paused) {
videoEl.play();
}
}
render() {
if (this.videoEl) {
this.updateVideoProp();
}
return (
<video ref={this.videoElRef}>
{ this.props.children }
</video>
);
}
}

class App extends Component {
constructor() {
super();
this.state = { paused: true };
this.onClick = this.onClick.bind(this);
}
onClick(){
this.setState(state => ({ ...state, paused: !this.state.paused }));
}
render() {
return (
<div id="app">
<Video paused={this.state.paused}>
<source
src="http://download.blender.org/peach/bigbuckbunny_movies/big_buck_bunny_480p_h264.mov"
type="video/mp4"
/>
</Video>
<p><button onClick={this.onClick}>{this.state.paused?'play':'pause'}</button></p>
</div>
);
}
}

ReactDOM.render(<App />, document.getElementById('root'));
video {
max-height: 80%;
max-width: 80%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

效果很好。然而,我发现它很老套。例如。修改 paused 属性实际上并不需要重新渲染组件,并且调用 updateVideoProp 方法作为 render 的副作用触发器。

我找不到实现此目的的正确模式。还有更好的办法吗?

最佳答案

我认为 updateVideoProp 方法的内容实际上属于 componentDidUpdate 方法,或者如果您想在调用渲染之前更改属性,请使用 componentWillRecieveProps方法。

关于javascript - 将 React props 桥接至仅 JS setter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42549679/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com