如何在react.js ES6中使用props设置状态

时间:2016-09-14 06:23:28

标签: reactjs ecmascript-6 webpack

我想知道,如何使用ES6

使用道具参数设置状态

之前:

Dim tfnSigned As String
tfnSigned = "Yes"

If tfnSigned = "Yes" Then
     SED_TFNSignedCheckBox.Checked = True
End If

现在我尝试这样做而且const MyComponent = React.createClass({ getInitialState: function() { return { name: this.props.name || 'Initial data...' }; } }); 不存在:

this.props

4 个答案:

答案 0 :(得分:6)

你只需要在构造函数方法中传递props参数:

import React from 'react';

class MyComponent extends React.Component {
    constructor(props) { // <-- this parameter
        super(props)
        this.state = {
            name: props.name || 'Joseph Flowers' // <-- then used like this
        };
    }
}

请注意,在某些情况下,它不是反模式:

  

(对于更复杂的逻辑,只需在方法中隔离计算。)

     

然而,如果你明确说明道具,它不是反模式   仅是组件内部控制状态的种子数据:   资料来源:https://facebook.github.io/react/tips/props-in-getInitialState-as-anti-pattern.html

BTW for ES6如果要设置默认属性,则必须在类声明的下一步声明:

import React from 'react';
import ReactDOM from 'react-dom';

class MyComponent extends React.Component {

    /**
    This is the ES7 way to use
    static propTypes = {            
        name: React.PropTypes.string,
    }

    static defaultProps = {         
        name: 'My default value using ES7'
    }
    */

    constructor(props) {
        super(props)
        // this still could be the best solutions in cases
        // of the unexpected values in the props sent 
        // for the out side component
        this.state = {
            name: props.name && props.name !== '' ? props.name :'Joseph Flowers';
        };
    }
}

// This is the ES6 way to use
MyComponent.propTypes = {
    name: React.PropTypes.string
}

MyComponent.defaultProps = {
    name: 'My default value'
}

ReactDOM.render(<MyComponent name="" />, document.getElementById('my-container-id'));

答案 1 :(得分:6)

实际上,您不需要为您尝试做的事情设置一个有状态的组件(反模式:https://facebook.github.io/react/tips/props-in-getInitialState-as-anti-pattern.html)。

相反,另一个更简单,更好的解决方案:

var allFiles = new List<string>();
string[] files = Directory.GetFiles("\\\\location\\tarballfiles\\", "*.tar.bz2", SearchOption.AllDirectories);
foreach (var file in files)
{
    // untar
    var filesFromTar = file.untar();

    foreach (var fileNameFromTar in filesFromTar)
    {
        allFiles.Add(fileNameFromTar);
    }
}

foreach (var allFile in allFiles)
{
    Console.WriteLine(allFile);
}

答案 2 :(得分:1)

您可以为无状态组件执行此操作

const MyComponent = (props) => {
 return <div>Hi {props.name || 'Joseph Flowers'}! </div>
}

答案 3 :(得分:0)

在es7中你可以像这样初始化状态。

class App extends React.Component {
    static propTypes = {
        title: React.PropTypes.string.isRequired,
    }   

    // or pass from parent Componet 
    static defaultProps = {
        title: 'hello',
    }

    state = {
        title: this.props.title
    }
    // ...
}