反应:子组件未接收通过“this.state”传递的道具

Posted

技术标签:

【中文标题】反应:子组件未接收通过“this.state”传递的道具【英文标题】:React: ChildComponent not recieving props passed through "this.state" 【发布时间】:2020-08-18 08:35:02 【问题描述】:

我一直在尝试使用 this.state 中声明的变量将道具传递给子组件“MovPlayer”,但似乎没有收到道具。由于页面呈现空白标签。

这是我的 MainComponent App.js

import React from "react";
import "./App.css";
import NavBar from "./NavBar";
import MovPlayer from "./MovPlayer";
import MovGallery from "./MovGallery";

class App extends React.Component 
  constructor() 
    super();
    this.state = 
      MovUrl: "https://somewebsite.com/files/videos/movie.mp4",
      MovName: "Movie Name",
      MovDesc: "Movie Description ....."
    ;
  
  render() 
    return (
      <div>
        <NavBar />
        <div>
          <MovPlayer
            url=this.state.MovUrl
            name=this.state.MovName
            desc=this.state.MovDesc
          />
          <MovGallery />
        </div>
      </div>
    );
  


export default App;

这是我的 ChildComponent MovPlayer.js

import React from "react";
import "./App.css";

function MovPlayer(props) 
  return (
    <div
      className="row"
      style= position: "relative", top: "1em", margin: "0 0em" 
    >
      <div className="col-md-4">
        <video controls="true" style= maxWidth: "100%" >
          <source src=props.MovUrl type="video/mp4" />
        </video>
      </div>
      <div className="col-md-8">
        <h2>props.MovName</h2>
        <h3 className="badge badge-danger">Now Playing</h3>
        <br />
        <small className="text-muted">props.MovDesc</small>
      </div>
    </div>
  );


export default MovPlayer;

最终的网页呈现如下,

<div class="row" style="position: relative; top: 1em; margin: 0px 0em;">
  <div class="col-md-4">
    <video controls="" style="max-width: 100%;">
    <source type="video/mp4">
    </video>
  </div>
  <div class="col-md-8">
    <h2></h2>
    <h3 class="badge badge-danger">Now Playing</h3><br>
    <small class="text-muted"></small>
  </div>
</div>

【问题讨论】:

【参考方案1】:

你是这样通过的:

<MovPlayer
  url=this.state.MovUrl      // should be accessed as props.url
  name=this.state.MovName    // should be accessed as props.name
  desc=this.state.MovDesc    // should be accessed as props.desc
/>

所以你应该使用:

props.name props.url props.desc

否则,这样改变你的道具:

<MovPlayer
  MovUrl=this.state.MovUrl      // can be accessed as props.MovUrl
  MovName=this.state.MovName    // can be accessed as props.MovName
  MovDesc=this.state.MovDesc    // can be accessed as props.MovDesc
/>

【讨论】:

以上是关于反应:子组件未接收通过“this.state”传递的道具的主要内容,如果未能解决你的问题,请参考以下文章

传递给反应组件子级的函数不接收函数上下文

React:将图像从父组件中的 this.state 传递给子组件

传递给子组件时道具未定义(反应钩子)

反应功能组件未从父组件更新 setState

Vue子组件未从父组件接收道具

React教程:父子组件传值(组件通信)