打字稿反应。破坏和传播对象

时间:2016-11-01 08:00:17

标签: reactjs typescript

尝试让我的子组件保持无状态(功能组件)。所以,我正在寻找将根组件状态值分配给其子组件的便捷方法。说,

interface IState {
  a: string;
  b: number;
  c: (e) => void;
}

然后

<ChildA {...this.state as { a: string, c }} />
<ChildB {...this.state as { c: (e) => void, b }} />

不幸的是,TypeScript目前不支持速记属性名称。这里有什么优雅的方法吗?

1 个答案:

答案 0 :(得分:1)

在最新的打字稿版本中,您可以使用扩展操作符,而无需进行转换...只要您的子组件具有正确的道具类型。

假设ChildA组件具有以下道具:

$TargetKeys = Get-ChildItem -Path 'HKLM:\SYSTEM\ControlSet001\Control\Class\' -Recurse -ErrorAction SilentlyContinue

ForEach($TestKey In $TargetKeys)
{
    $KeyName = $TestKey.Name.Replace("HKEY_LOCAL_MACHINE","HKLM:")
    $SubKeys = Get-ChildItem -Path $KeyName -ErrorAction SilentlyContinue
    ForEach($SubKey In $SubKeys)
    {
        If($SubKey -ne $null -or $SubKey -ne '')
        {
            $ErrorActionPreference = 'SilentlyContinue'
            $ItemKey = $SubKey.Name.Replace("HKEY_LOCAL_MACHINE","HKLM:")
            $PropNames = ForEach($PropName In (Get-ItemProperty -Path $ItemKey -ErrorAction SilentlyContinue | GM -MemberType Properties -ErrorAction SilentlyContinue | Select Name)) { $PropName.Name }
            If($PropNames -contains '*JumboPacket')
            {
                # Set to 9014 for enabling and 1514 for disabling
                Set-ItemProperty -Path $ItemKey -Name '*JumboPacket' -Value 9014 -ErrorAction SilentlyContinue
                If($?)
                {
                    Write-Host "'Jumbo Packets' enabled successfully for Network card." -ForegroundColor Green
                }
                Else
                {
                    Write-Host "Error while enabling 'Jumbo Packets' for Network card." -ForegroundColor Red
                }
            }
            $ErrorActionPreference = 'Continue'
        }
    }
}

要定义子无状态组件,请使用:

interface ChildAProps {
    a: string;
    c: (e) => void;
}

const ChildA : React.SFC<ChildAProps> = props => <div>{this.props.a}</div> 是React.StatelessComponent类的别名。稍后在父组件中使用带有状态的ChildA实例,只需写:

React.SFC