我是Reactjs的新手。我想要做的是在Main.js和SignupForm.js之间创建一个公共函数,下面是代码。
这是我的index.html代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="../assets/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" href="../assets/css/styles.css">
</head>
<body>
<div id="app"></div>
<script src="../assets/js/jquery.min.js"></script>
<script src="bundle.js"></script>
</body>
</html>
这是我的Main.js,它是完成ReactDOM渲染的主要组件:
var React = require('react');
var ReactDom = require('react-dom');
var SignupForm = require('./SignupForm.js');
var Modal = require('react-bootstrap/lib/Modal');
var Main = React.createClass({
getInitialState() {
return { showModal: false};
},
close() {
this.setState({ showModal: false });
},
open() {
this.setState({ showModal: true });
},
render: function () {
return (
<div>
<button className="btn-block btn btn-lg btn-info" onClick={this.open}> Open </button>
<Modal show={this.state.showModal} onHide={this.close} bsSize="small" aria-labelledby="contained-modal-title-sm" enforceFocus >
<Modal.Header closeButton>
<Modal.Title className="text-center tb_spacing">Sign up free to connect with the
right one</Modal.Title>
<SignupForm />
</Modal.Header>
</Modal>
<div>
);
}
});
ReactDOM.render(<Main/>, document.getElementById('app'));
我的其他组件SignupForm.js代码是:
var React = require('react');
var SignupForm = React.createClass ({
render : function() {
return (
<form id="signup">
<div className="form-group" id="formControlsEmail">
<label className="control-label">Email</label>
<input type="email" className="form-control" placeholder="Enter email" id="layer_email"/>
</div>
<div className="form-group" id="formControlsPassword">
<label className="control-label">Password</label>
<input type="password" className="form-control" placeholder="Enter password" id="layer_password1"/>
</div>
<div className="form-group">
<label className="control-label">Gender </label>
<label className="radio-inline" >
<input type="radio" name="male" />
Male
</label>
{' '}
<label className="radio-inline" >
<input type="radio" name="female" />
Female
</label>
{' '}
</div>
<button type="submit" className="btn-block btn btn-lg btn-info" onClick={this.close}>
Next
</button>
</form>
)
}
});
module.exports = SignupForm;
从我的SignupForm.js我试图执行main.js中的函数close()
提前谢谢。
答案 0 :(得分:1)
在您的Main.js中,您可以将close
方法作为prop
传递给SignUpForm
<SignupForm close={this.close} />
然后在SignupForm
中,您可以使用onClick={this.props.close}
修改强>
虽然上述解决方案可行,但它会使SignupForm
组件不可重复使用。我建议你将Modal
JSX代码插入到SignupForm
组件中,它应该控制它自己的状态。如果你想从外面打开它,它应该是元素上的道具,类似于<SignupForm isOpen={isOpen}>
。