我有两个组成部分:
父组件是类组件,子组件是函数组件。从父组件调用子方法的最佳实践是什么?
这些组件的目标是能够动态加载svg文件。
父组件:
class UnitMonitor extends PureComponent {
  constructor() {
    super();
  }
  state = {
    img: null,
  };
  onChangeShcema = schemaID => {
    axios.get("/api/schemata/get-schemata-nodes/" + schemaID).then(response => {
      let path = response.data["0"]["file"];
      // call loadFile function of child component is needed
    });
render() {
    return (
      <Row type="flex" className="">
        <Col span={25}>
          <SvgViewer />
        </Col>
      </Row>
    );
  }
  };儿童部分:
const SvgViewer = () => {
  const loadFile = path => { 
    let svgFile = require("./images/" + path);
    const svg = document.querySelector("#svgobject");
    svg.setAttribute("data", svgFile);
  };
  return (
    <div className="unit-schema-container1">
      <object id="svgobject" type="image/svg+xml" data={null}></object>
    </div>
  );
};
export default SvgViewer;发布于 2019-12-26 07:48:46
在React中,尝试在父级上运行子方法并不是一个好主意,因为它主要是一个糟糕设计的标志。因为您希望动态运行SVG,所以可以传递带有路径或所需内容的支柱,以便动态加载它。但是,如果您坚定地在父服务器上运行该方法,请检查这个post如何执行它。
发布于 2019-12-26 07:56:50
在父组件中定义所有函数,并将其作为道具传递给子组件。
尝尝这个
class UnitMonitor extends PureComponent {
  constructor() {
    super();
  }
  state = {
    img: null,
  };
  onChangeShcema = schemaID => {
    axios.get("/api/schemata/get-schemata-nodes/" + schemaID).then(response => {
      let path = response.data["0"]["file"];
       this.setState({img: path});
      // call loadFile function of child component is needed
    });
render() {
    return (
      <Row type="flex" className="">
        <Col span={25}>
          <SvgViewer onChangeShcema ={this.onChangeShcema} image={this.state.img} />
        </Col>
      </Row>
    );
  }
  };在子组件中像这样访问
onChange={props.onChangeShcema}或onClick={props.onChangeShcema}
img={props.image}发布于 2019-12-26 07:58:42
使用临时道具。例如,单击“计数”。useEffect钩子方法中的句柄单击计数当props.count被更改时,调用函数)
在子组件中,使用以下代码段:
useEffect(() =>Call your function is here, [props.count ]);https://stackoverflow.com/questions/59485383
复制相似问题