【发布时间】:2018-01-14 01:12:49
【问题描述】:
我在一个名为 ts.js 的文件中有一个 react 组件:
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
export default class Ts extends React.Component {
constructor(props) {
super(props);
var expected = {
lowercase:'Onlylowercase',
snakeCase:'justSnakeCase',
ProperCase: 'AndProperCase'
};
console.log("expected:",expected);
console.log("props:",props);
console.log("this.props",this.props);
console.log("props.lowercase",props.lowercase);
this.state={'lowercase':this.props.lowercase};
};
render() {
return NULL;
}
}
if (document.getElementById('ts')) {
ReactDOM.render(<Ts />, document.getElementById('ts'));
}
我也有一个 html 页面,从中调用它:
<html>
<head>
<title>My TS</title>
</head>
<body>
<Ts lowercase="onlylowercase" id="ts" snakeCase="justSnakeCase" ProperCase="AndProperCase">
</Ts>
<script src="{{ asset('js/app.js') }}"></script>
</body>
</html>
我的问题是我无法在构造函数中将值 lowercase="onlylowercase" id="ts" snakeCase="justSnakeCase" ProperCase="AndProperCase" 识别为道具。我需要从 html 中传入一些东西来填充组件的初始状态。
当我打开 Chrome 控制台打开 HTML 时,我得到:
expected: {lowercase: "Onlylowercase", snakeCase: "justSnakeCase", ProperCase: "AndProperCase"}
props: {}
__proto__: Object
or it is this.props?: {}
__proto__: Object
props.lowercase undefined
this.props.lowercase undefined
undefined
undefined
我希望 props 是一个带有小写、snakeCase 和 ProperCase 属性的 javascript 对象,就像预期的 var 一样。
我认为我不需要使用 componentWillReceiveProps - 因为我正在尝试遵循此处文档中描述的模式: https://reactjs.org/docs/react-component.html#constructor 并将 props 作为 html 属性传入,如下所述: https://reactjs.org/docs/components-and-props.html
我已经从这篇文章中排除了节点模块和 javascript 的详细信息,因为正在调用 Ts 组件的构造函数,这表明 Ts 类在“那里”并且我的 npm 配置正常 - 它包括反应和其他必需的模块。 {{asset() }} 函数是 Laravel 函数。 html 是 Laravel 应用中刀片模板的一部分。
谁能看出我做错了什么?
【问题讨论】:
-
不是反应用户,console.log on props 和 this.props 它给你一个对象。然后你试图将该对象转换为小写!
-
我希望 props 是一个包含小写、snakeCase 和 ProperCase 属性的对象。相反,它是一个空对象,仅包含所有对象包含的原型内容。我已经根据您的反馈更新了上面的帖子,谢谢。
-
在此处查看我在 React 组件中注入 props 的答案:stackoverflow.com/a/54158247/579890