将道具从一个组件传递到另一组件

时间:2018-11-30 07:33:25

标签: reactjs

我正在尝试将值"red"index.js传递到box.js,但仍无法正常工作。基本上,我有一个定义box属性的组件,我想将背景颜色“红色”从index.js传递到Box.js组件。

// Box.js
import React from "react";
const box = {
  // here i would like to get the vlue name assign it to background
  background: this.props.name,
  width: "250px",
  height: "250px"
  // more code that defines how the box looks like here
};

export default Box;

  /// index.js
import React, { Component } from "react";
import { render } from "react-dom";
import Box from "./Box";
  render() {
 

    return (
     // when calling Box, I would like to pass the value red to varivable name as shown below
    <Box name="red"></Box>
    )
   
}

我想念什么?

2 个答案:

答案 0 :(得分:1)

您需要创建一个适当的组件:

// box.js
import React from "react";
const Box = (props) => {
  // here i would like to get the value name assign it to background
  const background = props.name;
  const width = "250px";
  const height = "250px";
  // more code that defines how the box looks like here
  return (
    // jsx code goes here
  );
};

export default Box;

在第二个片段中,您没有正确使用它

// index.js
import React from "react";
import Box from "./box"; // assuming that the file name is box.js and it is in the same folder

const BoxDisplay = (props) => {
    return (
       <Box name="red"/>
    );
};

export default BoxDisplay;

或者如果您需要实际的组件:

// index.js
import React, {Component} from "react";
import Box from "./box";

export default class BoxDisplay extends Component({
    constructor(props) {
        super(props)
        this.state = { //any initial state you want}
    }
    render() {
        return (<Box name="red"/>)
    }
});

答案 1 :(得分:0)

这个问题有些混乱,请帮助我们详细了解您的问题。

  • 您的默认导出名称是“ card”,并且您正在尝试导入 “盒子”。
  • 主要源代码是什么意思?
  • 您的index.js没有正确的组件语法

请注意,如果您不使用基于类的组件或构造函数,而不能使用“ props”,则不能使用“ this.props”

尝试如下更改Box组件:

const Box = (props) => {
    return <p style={{background: props.name}}> Content </p>
}