score:0

you should provide link to this function via props to children or through context.

class parent extends react.component {
constructor(props: any) {
    super(props);
    this.changedatasource = this.changedatasource.bind(this);
}
state = { value: 'old' }

forceupdate() {
    console.log('forceupdate');
}

changedatasource() {
    this.setstate({ value: 'updated' });
    this.forceupdate();
}

render() {
    return (
        <div>
            <h1>parent</h1>
            <p>{this.state.value}</p>
            <child func={this.changedatasource} />
        </div>
    )
  }
}

in child.tsx:

type function = (source: any) => void;

type childprops = {
  func: function
}


const child = ({ func }: childprops) => {
  return (
    <div>
        <h2>child</h2>
        <button onclick={func}>child button</button>
    </div>
  )
}

with context it will be like this:

const context = react.createcontext<(() => void) | undefined>(undefined);

const child = () => {
  const func = react.usecontext(context);

  return (
    <div>
        <h2>child</h2>
        <button onclick={func}>child button</button>
    </div>
  )
}

class parent extends react.component {
  constructor(props: any) {
    super(props);
    this.changedatasource = this.changedatasource.bind(this);
  }
  state = { value: 'old' }

  forceupdate() {
    console.log('forceupdate');
  }

  changedatasource() {
    this.setstate({ value: 'updated' });
    this.forceupdate();
  }

  render() {
    return (
        <context.provider value={this.changedatasource}>
            <div>
                <h1>parent</h1>
                <p>{this.state.value}</p>
                {/* deeep in tree */}
                <child />
            </div>
        </context.provider>
    )
  }
}

Related Query

More Query from same tag