据我所知,继承使孩子可以使用父级的属性/方法。但是在研发期间,我发现了一个代码段,其中父组件也使用子组件方法。我进行了搜索,但在此背后找不到适当的解释。这是代码:
表单组件:
original_custom_price
登录组件:
base_cost
输入组件:
import React from 'react';
import Input from "./input";
class Form extends React.Component{
state = {
data: {},
errors: {}
};
handleChange = ({currentTarget: input}) => {
const data = {...this.state.data};
data[input.name] = input.value;
this.setState({data});
};
handleSubmit = (e) => {
e.preventDefault();
//Some validation
this.doSubmit();
};
renderInput(name, label, type) {
const {data,errors} = this.state;
return (
<Input
type={type}
name={name}
label={label}
value={data[name]}
error={errors[name]}
onChange={this.handleChange}/>
);
};
renderButton(label) {
return (
<button>{label}</button>
);
}
}
export default Form;
此处,登录组件扩展了 Form 组件。因此,登录可以使用表单的方法。但是 Form 如何在其import React from 'react';
import Form from "./common/form";
class Login extends Form{
state = {
data: {
username: "",
password: "",
},
errors: {},
};
doSubmit = () => {
console.log(this.state.data);
};
render() {
return (
<div>
<h1>Login</h1>
<form onSubmit={this.handleSubmit}>
{this.renderInput("username", "Username", "text")}
{this.renderInput("password", "Password", "password")}
{this.renderButton("Submit")}
</form>
</div>
);
}
}
export default Login;
方法中使用登录的import React from 'react';
const Input = ({name, label, error, ...rest}) => {
return (
<div className="form-group">
<label htmlFor={name}>{label}</label>
<input className="from-control" {...rest} name={name} id={name}/>
{error && <div>{error}</div>}
</div>
);
};
export default Input;
方法?