React Props - 无法获取数据

时间:2017-12-20 21:33:00

标签: reactjs

当我定义如下变量(var myCheese)时,我无法使用React Props;



    function TodoComponent(props) {
        return <div>
            <h1> Move Name : {props.name}</h1>
            <h2> Genre : {props.genre}</h2>
            <p>Cheese nameis: {props.nameis}</p>
            <p>Cheese smellFactor: {props.smellFactor}</p>
            <p>Cheese price: {props.price}</p>
        </div>;
    }
    var myCheese = { nameis: 'Camembert', smellFactor: 'Extreme pong', price: '3.50' };
    ReactDOM.render(
        <div>
            <TodoComponent name="Gladiator" genre="Action" />
            <TodoComponent name="Goodfellas" genre="Drama,Gangsters" />
            <TodoComponent cheese={myCheese} />
        </div>,
        document.getElementById('todo-wrapper')
    );
&#13;
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="todo-wrapper"></div>
&#13;
&#13;
&#13;

用于名称和流派的是工作但是奶酪不起作用。我无法从中获取数据。谢谢你的帮助!

2 个答案:

答案 0 :(得分:0)

您正在将名为“cheese”的道具传递给您的 TodoComponent ,但您实际上并没有对该道具做任何事情。您似乎期望传递给“奶酪”道具的对象的属性以某种方式分解为多个道具“nameis”,“smellFactor”和“price”,但这并不是道具如何运作。

您有两种选择:

<强> 1。将每个“myCheese”属性作为单独的道具传递

<TodoComponent 
    nameis={myCheese.nameis}
    smellFactor={myCheese.smellFactor}
    price={myCheese.price}
/>

...或...

<强> 2。在组件中使用“cheese”prop

function TodoComponent(props) {
    return <div>
        <p>Cheese nameis: {props.cheese.nameis}</p>
        <p>Cheese smellFactor: {props.cheese.smellFactor}</p>
        <p>Cheese price: {props.cheese.price}</p>
    </div>;
}

答案 1 :(得分:0)

让它运行的最简单方法是将组件更改为:

const TodoComponent = ({
  name,
  genre,
  nameis,
  smellFactor,
  price
}) => (
  <div>
    <h1> Move Name : {name}</h1>
    <h2> Genre : {genre}</h2>
    <p>Cheese nameis: {nameis}</p>
    <p>Cheese smellFactor: {smellFactor}</p>
    <p>Cheese price: {price}</p>
  </div>;
)

并根据需要使用它:

const myCheese = {
  // here Object properties should much your React component props
  name: 'default', // default value otherwise it will be undefined
  gerne: 'default', // same as above 
  nameis: 'Camembert',
  smellFactor: 'Extreme pong',
  price: '3.50'
};

ReactDOM.render(
  <div>
    <TodoComponent name="Gladiator" genre="Action" /> //
    <TodoComponent name="Goodfellas" genre="Drama,Gangsters" /> // these two are harcoded
    <TodoComponent {...myCheese} /> // here your props will be passed dynamicly
  </div>,
  document.getElementById('todo-wrapper')
);

希望它会对你有所帮助。