2 つのコンポーネントがあります:
- 親コンポーネント
- 子コンポーネント
親から子のメソッドを呼び出そうとしましたが、次の方法を試しましたが、結果が得られませんでした。
class Parent extends Component {
render() {
return (
<Child>
<button onClick={Child.getAlert()}>Click</button>
</Child>
);
}
}
class Child extends Component {
getAlert() {
alert('clicked');
}
render() {
return (
<h1 ref="hello">Hello</h1>
);
}
}
親から子のメソッドを呼び出す方法はありますか?
注: 子コンポーネントと親コンポーネントは 2 つの異なるファイルにあります。
ベストアンサー1
まず最初に、これは React の世界では一般的には行われないやり方だということを述べておきます。通常、やりたいことは、プロパティで子に機能を渡し、イベントで子からの通知を渡すことです (または、もっと良いのは、dispatch
)。
しかし、子コンポーネントに命令型メソッドを公開する必要がある場合は、次のようにします。参照これは脱出ハッチであり、通常はより優れた設計が利用可能であることを示していることに注意してください。
これまで、refsはクラスベースのコンポーネントでのみサポートされていました。Reactフックもはやそうではない
フックを使ったモダンな React ( v16.8+
)
const { forwardRef, useRef, useImperativeHandle } = React;
// We need to wrap component in `forwardRef` in order to gain
// access to the ref object that is assigned using the `ref` prop.
// This ref is passed as the second parameter to the function component.
const Child = forwardRef((props, ref) => {
// The component instance will be extended
// with whatever you return from the callback passed
// as the second argument
useImperativeHandle(ref, () => ({
getAlert() {
alert("getAlert from Child");
}
}));
return <h1>Hi</h1>;
});
const Parent = () => {
// In order to gain access to the child component instance,
// you need to assign it to a `ref`, so we call `useRef()` to get one
const childRef = useRef();
return (
<div>
<Child ref={childRef} />
<button onClick={() => childRef.current.getAlert()}>Click</button>
</div>
);
};
ReactDOM.render(
<Parent />,
document.getElementById('root')
);
<script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>
<div id="root"></div>
のドキュメントuseImperativeHandle()
はここ:
useImperativeHandle
を使用するときに親コンポーネントに公開されるインスタンス値をカスタマイズしますref
。
クラスコンポーネントを使用したレガシー API ( )>= [email protected]
const { Component } = React;
class Parent extends Component {
constructor(props) {
super(props);
this.child = React.createRef();
}
onClick = () => {
this.child.current.getAlert();
};
render() {
return (
<div>
<Child ref={this.child} />
<button onClick={this.onClick}>Click</button>
</div>
);
}
}
class Child extends Component {
getAlert() {
alert('getAlert from Child');
}
render() {
return <h1>Hello</h1>;
}
}
ReactDOM.render(<Parent />, document.getElementById('root'));
<script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>
<div id="root"></div>
コールバック参照 API
コールバックスタイルの ref は、これを実現するためのもう 1 つのアプローチですが、最新の React ではそれほど一般的ではありません。
const { Component } = React;
const { render } = ReactDOM;
class Parent extends Component {
render() {
return (
<div>
<Child ref={instance => { this.child = instance; }} />
<button onClick={() => { this.child.getAlert(); }}>Click</button>
</div>
);
}
}
class Child extends Component {
getAlert() {
alert('clicked');
}
render() {
return (
<h1>Hello</h1>
);
}
}
render(
<Parent />,
document.getElementById('app')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>