Dan*_*Dan 7 javascript reactjs
这是我第一次创建 React 应用程序。
我想将按钮从 index.js 传递给使用hooks 的表组件。
Declaration:
const testButton = () => {
return (
<React.Fragment>
<button>Test1</button>
<button>Test2</button>
<button>Test3</button>
<button>Test4</button>
<button>Test5</button>
</React.Fragment>
);
};
Run Code Online (Sandbox Code Playgroud)
将其传递给 Table 组件
return (
<React.Fragment>
<TestTable
{...{
testButton}} />
</React.Fragment>
Run Code Online (Sandbox Code Playgroud)
然后,表格组件将使用它来呈现表格,包括按钮。
export default function TestTable({
testButton,
...props
})
return (
{testButton});
Run Code Online (Sandbox Code Playgroud)
我做得对吗?
如何从 index.js 导出它,在 Table component.js 中导入,并在 Table 组件中呈现?
谢谢你。
小智 15
我想你想要的是:
const TestTable = ({ children }) => {
return (
<table>
<tr>
<td>Something...</td>
<td>{children}</td>
</tr>
</table>
)
}
Run Code Online (Sandbox Code Playgroud)
进而:
const App = () => {
return (
<TestTable>
<button>Test 1</button>
<button>Test 2</button>
<button>Test 3</button>
</TestTable>
)
}
Run Code Online (Sandbox Code Playgroud)
希望能帮助到你!
React 库促进组件组合。有关此模式的最新文章,请阅读 Robin Wieruch 的文章
您可以重构 TestTable 组件,如下所示:
这里我添加了一个codesandbox示例:https ://codesandbox.io/embed/smoosh-cache-ytfky
import React from 'react'
export default function TestTable(props) {
return (
<React.Fragment>
{props.children}
</React.Fragment>
)
}
Run Code Online (Sandbox Code Playgroud)
您的 TestButton 组件可以保持基本相同。您需要将导出关键字添加到组件的开头。实际上,这些组件只是普通的旧功能。要了解有关不同风格的导出函数的更多信息,请参阅Alex Rauschmayer 的精彩描述。对于使用默认导出还是命名导出存在争议,我个人更喜欢命名导出,它更具声明性,而且更容易让我看到发生了什么。
export default function TestButton() {
return (
<React.Fragment>
<button>Test1</button>
<button>Test2</button>
<button>Test3</button>
<button>Test4</button>
<button>Test5</button>
</React.Fragment>
);
};
Run Code Online (Sandbox Code Playgroud)
您现在可以在另一个函数中组合两个组件,如下所示:
export function DisplayTable(props) {
return (
<TestTable>
<TestButton />
</TestTable>
)
}
Run Code Online (Sandbox Code Playgroud)
笔记:
至于 React Hooks,它们是自 16.8 以来对 React 的新介绍,它真正解决了能够在不使用类的情况下处理状态和副作用的特定用例。请参阅原始文档以获得详细的描述
在你的index.js(返回按钮的地方):
const TestButtons = () => (
<>
<button>Test1</button>
<button>Test2</button>
<button>Test3</button>
<button>Test4</button>
<button>Test5</button>
</>
)
export default TestButtons
Run Code Online (Sandbox Code Playgroud)
然后,在你的table.js:
import TestButtons from 'path/to/index.js'
const TestTable = () => (
<TestButtons />
)
Run Code Online (Sandbox Code Playgroud)
您应该使用该import语句从另一个文件导入组件。