0

我已经开始学习反应。

我不确定在使用 redux-connect 时如何在(父子)组件之间传递值。

当我直接导出没有connect或的类时效果很好compose

错误

Type '{ dataFromParent: string; parentCallback: (data: any) => void; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<Component<unknown, any, any>> & Readonly<unknown> & Readonly<{ children?: ReactNode; }>'.
  Property 'dataFromParent' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<Component<unknown, any, any>> & Readonly<unknown> & Readonly<{ children?: ReactNode; }>'.

父.tsx

 <Child
   dataFromParent={this.state.data}
   parentCallback={this.parentCalled}
 />

孩子.tsx

import React from "react";
import "./Child.css";
import TreeView from "@material-ui/lab/TreeView";
import TreeItem from "@material-ui/lab/TreeItem";
import {
  Button,
  withStyles,
  WithStyles,
  Theme,
  StyleRules,
  createStyles
} from "@material-ui/core";
import { connect } from "react-redux";
import compose from "recompose/compose";
import { AppState } from "Store";

interface MyProps extends WithStyles<typeof styles> {
  dataFromParent: any; // value from parent
  parentCallback: (val: string) => void; // sending value to parent
}

// state
interface MyState {}

const styles = (theme: Theme): StyleRules => createStyles({});

class Child extends React.Component<MyProps, MyState> {
  constructor(props: any) {
    super(props);
    this.state = {};
    this.callParent = this.callParent.bind(this);
  }

  componentDidMount() {}

  public callParent() {
    // child to parent
    this.props.parentCallback("value sent from child");
  }
  public render() {
    return (
      <div className="treeStyle">
        <div> data from parent: {this.props.dataFromParent}</div>
        <Button onClick={this.callParent}>
          send to parent
        </Button>
       </div>
    );
  }
}

const mapStateToProps = (state: AppState) => ({});
export default compose(withStyles(styles), connect(mapStateToProps, {}))(Child);
4

1 回答 1

1

您也可以在不使用 recompose 的情况下实现它,例如:

export default connect(mapStateToProps, mapDispatchToProps)(withStyles(styles)(Child));

此外,您可能需要更改props: anyprops: MyProps避免 tslint/eslint 发出任何警告

于 2020-03-26T13:30:04.133 回答