在函数react js中传递组件& props。

问题描述 投票:0回答:1

我有2个组件& 我想把数据从父组件传递到子组件,我被卡住了,无法把数据传递到子组件,并显示或渲染子组件。

有什么技术可以将道具传递给子组件&渲染它?

当我在开发工具上看到控制台时,除了 console.log 代码外,没有任何问题发生。

import React, {Component} from 'react';
import ReactDOM from'react-dom';
import {
  BrowserRouter as Router,
  Switch,
  Route,
  Link
} from "react-router-dom";
//props.keyword
const keyword = 'avenger';
const API = `https://api.themoviedb.org/3/search/movie?api_key=341c549444f65b6a022eea5fc24f5b77&language=en-US&query=${keyword}&page=1&include_adult=false`;
const DEFAULT_QUERY = 'redux';

class MovieSearch extends Component{
  constructor(props){
    super(props);
    this.state={
      movies:[]
    }
  }

  componentDidMount(){
    fetch(API + DEFAULT_QUERY)
      .then(response=>response.json())
      .then(data=>{
        this.setState({movies:data.results})
      })
    }
    
  render(){
    const {movies} = this.state;
    return(
      <div className="row container">
          {movies.map(movie =>
          <div className="col-md-4">
            <div className="card" style={{width: '15rem'}} key={movie.id}>
              <img src="" className="card-img-top" alt="..."/>
              <div className="card-body">
                <h5 className="card-title">{movie.title}</h5>
                <p>{movie.id}</p>
                <Link to="/movie/detail">Detail</Link>
              </div>
            </div>
          </div>
          )}      
      </div>
    )
  }
}

export default MovieSearch;
import React, { Component } from"react";
import {
  BrowserRouter as Router,
  Switch,
  Route,
  Link
} from "react-router-dom";
//component
import Jumbotron from "./jumbotron";
import MovieList from "./movieList";
import MovieSearch from"./MovieSearch";
import Movie from"./Movie";


//HOC
const idMovie = (WrappedComponent)=>{
  class IdMovie extends Component{
    constructor(props){
      super(props)
      this.state={}
    }
  }
}


//route start here

class Main extends Component{
  constructor(props){
    super(props)
    this.state={
      keyword: ''
    }

    this.handleInput = this.handleInput.bind(this)
    this.handleSubmit = this.handleSubmit.bind(this)
  }

  handleInput(event){
    this.setState({keyword:event.target.value})
  }

  handleSubmit(event){
    
    console.log(this.state.keyword)
    event.preventDefault()
  }
  
  render(){
    return (
      <Router>
        <nav className="navbar navbar-expand-lg navbar-dark bg-dark">
          <Link className="navbar-brand" to="/">Carifilm</Link>
          <button className="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
            <span className="navbar-toggler-icon"></span>
          </button>

          <div className="collapse navbar-collapse" id="navbarSupportedContent">
              <ul className="navbar-nav mr-auto">
                <li className="nav-item active">
                  <Link className="nav-link" to="/">Home <span className="sr-only">(current)</span></Link>
                </li>
                <li className="nav-item">
                  <Link className="nav-link" to="/movies">Movies</Link>
                </li>
                <li className="nav-item">
                  <Link className="nav-link" to="/search-movie">Cari film</Link>
                </li>
              </ul>
              <form className="form-inline my-2 my-lg-0" onSubmit={this.handleSubmit}>
                <input className="form-control mr-sm-2"
                      type="search" placeholder="Search"
                      aria-label="Search"
                      value={this.state.keyword} 
                      onChange={this.handleInput}/>
                <button className="btn btn-outline-success my-2 my-sm-0" type="submit" value="submit">Search</button>
              </form>
            </div>
        </nav>
        <Switch>
          <Route exact path="/">
            <Home/>
          </Route>
          <Route path="/movies">
            <Movies/>
          </Route>
          <Route path="/movie/detail">
            <MovieDetail/>
          </Route>
          <Route path="/search-movie">
            <CariFilm/>
          </Route>
        </Switch>
      </Router>
    )}
}

export default Main;

function Home(){
  return(
    <Jumbotron/>
  )
}

function Movies(){
  return(
    <MovieList/>
  )
}

function MovieDetail(){
  return(
    <Movie/>
  )
}

function CariFilm(props){
  return(
    <MovieSearch/>
  )
}
reactjs api react-props react-component
1个回答
0
投票

请检查这个例子。我在这里传递了 物品 到我的子组件中,并在子组件中显示项目。

父组件

import React, {Component, useEffect, useState} from 'react';
import {PChild} from "./PChild";

export class Parent extends Component {
    constructor(props) {
        super(props);
        this.state = {items: []};
    }

    componentDidMount() {
        let json = [];
        json.push({track: { id:1, name: 'Black Sabbath, from the album Black Sabbath (1970)'}});
        json.push({track: { id:2, name: 'Blackfield, from the album Blackfield (2004)'}});
        json.push({track: { id:3, name: 'Bo Diddley, from the album Bo Diddley (1958)'}});
        json.push({track: { id:4, name: 'Damn Yankees, from the album Damn Yankees (1990)'}});
        this.setState({items: json});
    }

    render() {
        return (
            <div>
                <PChild items={this.state.items} name="Khabir"/>
            </div>
        );
    }
}

儿童

import React, {useEffect, useState} from 'react';

// Parent to Child communication
export class PChild extends React.Component {

    componentDidUpdate() {
        console.log(this.props.items);
        console.log(this.props.name);
    }

    render() {
        return (
            <div>
                {this.props.items.map((item, i) => {
                    return <li key={item.track.id}>
                        {(`Item ${i+1} - ${item.track.name}`)}
                    </li>
                })}
            </div>
        );
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.