假设我有一个带有按钮的组件(header.jsx)。单击该按钮时,我想打开一个使用 Material UI 创建的对话框。这个对话框组件在另一个我称为 dialog.jsx 的文件中。我知道如何在一个文件中完成所有操作:只需创建一个链接到按钮的函数并在对话框标记上调用显示事件。但是,如果我要将这两个分成单独文件中的组件,我该如何完成呢?
3 回答
ref
您可以通过将道具传递给Dialog
组件来完成您想要做的事情。Dialog
然后,您可以通过引用组件this.refs
内的对象来调用组件上的方法Parent
。这是一个 CodePen 展示了这一点。http://codepen.io/anon/pen/pgNVpa显然,CodePen 中的代码都在一个文件中。以下是您将如何在多个文件中执行此操作。
现在,仅仅因为你能做到这一点并不意味着你应该这样做。我会推荐@HaZardouS 在他的回答中采用的方法。这就是经典的 React 模式。在 React 文档中,他们警告不要过度使用refs
.
https://facebook.github.io/react/docs/more-about-refs.html
如果你没有用 React 编写过几个应用程序,你的第一个倾向通常是尝试在你的应用程序中使用 refs 来“让事情发生”。如果是这种情况,请花点时间更批判地思考在组件层次结构中应该拥有状态的位置。通常,很明显“拥有”该状态的适当位置位于层次结构中的更高级别。将状态放置在那里通常会消除使用 refs 来“让事情发生”的任何愿望——相反,数据流通常会实现您的目标。
对话框.jsx
class Dialog extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {
open: false
};
this.open = this.open.bind(this);
this.close = this.close.bind(this);
}
open() {
this.setState({
open: true
});
}
close() {
this.setState({
open: false
});
}
render() {
if (this.state.open) return <p>Dialog is open.</p>;
else return <p>Dialog is closed.</p>
}
}
export default Dialog;
父.jsx
import Dialog from './Dialog';
class Parent extends React.Component {
constructor(props, context) {
super(props, context);
this.openDialog = this.openDialog.bind(this);
this.closeDialog = this.closeDialog.bind(this);
}
openDialog() {
this.refs.dialog.open();
}
closeDialog() {
this.refs.dialog.close();
}
render() {
return (
<div>
<button onClick={this.openDialog}>Open Dialog</button>
<button onClick={this.closeDialog}>Close Dialog</button>
<Dialog ref="dialog" />
</div>
);
}
}
React.render(<Parent />, document.querySelector('#react-app'));
您可以使用用户ReactDom.render
方法在特定操作上呈现组件
假设我有 dialog.jsx 之类的
var Dialog=React.createClass({
//render function goes here
});
module.exports=Dialog
我想在按钮点击时使用这个组件,那么你的父组件应该像
var parent=React.createClass({
click:function()
{
ReactDom.render(<Dialog />,document.getElementById("child");
},
render:function()
{
return(
<div>
<div id="child">
<div>
<button onClick={this.click} />
</div>
)
}
});
希望这可以帮助你
像这样做....
var React = import('react'),
Dialog = require("path.to.dialog.jsx"),
header = React.createClass({
componentWillReceiveProps: function(){
this.setState({"showDialog" : false});
},
onButtonClick : function(){
this.setState({"showDialog" : true});
},
render: function(){
return (
<div>
<Your other layout>
<Button text="Open dialog" click={this.onButtonClick} />
</Your other layout>
<Dialog show={this.state.showDialog} />
</div>
);
}
});