首先,我是为了 php 背景而来的,我目前正在 react 中构建一个中间件,我这样做的方式是这样的:
class Middleware extends React.Component {
funcOne(data) {
return data;
}
funcTwo(data) {
return (
<div>
{ data }
<br />
{ this.funcThree('Third function') }
</div>
);
}
}
class MyComponent extends Middleware {
funcOne(data) {
return `Rewrite of ${data}`;
}
funcThree(data) {
return data;
}
render() {
return (
<div>
{ this.funcOne('First function') }
{ this.funcTwo('Second function') }
</div>
);
}
}
class MySecondComponent extends Middleware {
funcThree(data) {
return data;
}
render() {
return (
<div>
{ this.funcOne('First function') }
{ this.funcTwo('Second function') }
</div>
);
}
}
ReactDOM.render(
<div>
<MyComponent />
<hr />
<MySecondComponent />
</div>,
document.getElementById('root'),
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.js"></script>
<div id="root"></div>
但是,我真的找不到任何关于是否这样做的文档。那么,这是错的吗?如果是这样,我应该怎么做?
在更新的代码中,只需创建一个用于funcTwo
的组件并向其传递一个 prop:
function funcOne () {
return 'First function';
}
function Two (props) {
return (
<div>
Second function
<br />
{ props.three }
</div>
);
}
//...
render() {
return (
<div>
{ funcOne() }
<br />
<Two three={this.funcThree()} />
</div>
);
}
我从未见过任何必须在 React 中使用继承的用例。在您的情况下,只需创建组件或普通函数。此外,组件也可以是一个普通函数:
这可以是一个组件:
function One (props) {
return <h1>hello</h1>
}
你像这样使用它:
<One />
或者,如果你只需要字符串,只需编写函数:
function funcOne () {
return 'First function';
}
function funcTwo () {
return 'Second function';
}
// ...
render() {
return (
<div>
{ funcOne() }
<br />
{ funcTwo() }
</div>
);
}
因此,您根本不需要继承。在 JavaScript 中,尤其是 React,你应该尝试以更实用的方式思考。您会发现它非常强大和灵活。
您可以在此处找到有关组件组成的官方文档:https://facebook.github.io/react/docs/composition-vs-inheritance.html
我还建议您阅读以下内容:https://facebook.github.io/react/docs/thinking-in-react.html
您要实现的内容通常称为高阶组件。这是详细的文档。
我认为您在 react 世界中重用的方式是创建接受组件并返回具有附加功能的新组件的函数,将其包装在向其添加功能的组件中。
这可以通过将要"派生"功能的组件传递给函数,或者直接将其包装在"包装器"组件中并访问 props.children
属性中的"包装"组件来完成。
const componentWithDropTargetCapabilities = addDragAndDrop(MyComponent)
或
<DropTarget>
<MyComponent />
</DropTarget>
这些被称为"高阶分量"(HOC(:https://facebook.github.io/react/docs/higher-order-components.html
例如,看看 ar react-router 代码:https://github.com/ReactTraining/react-router