parent 到 child 通信 - reactjs 与 tsx 和 redux 连接

parent to child communication - reactjs with tsx and redux connect

我已经开始学习react了。

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

当我直接导出 class 而不使用 connectcompose

时效果很好

错误

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; }>'.

parent.tsx

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

child.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);

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

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

此外,您可能希望将 props: any 更改为 props: MyProps 以避免 tslint/eslint

发出任何警告