如何使用ink react
安装 Ink 和 React
在项目目录下运行以下命令安装 Ink 和 React 的依赖:
npm install ink react
创建基础组件
创建一个简单的 Ink 组件,例如 HelloWorld.js:
import React from 'react';
import { Text } from 'ink';
const HelloWorld = () => <Text color="green">Hello World!</Text>;
export default HelloWorld;
渲染组件到终端
创建主入口文件 index.js,使用 render 方法将组件渲染到终端:
import React from 'react';
import { render } from 'ink';
import HelloWorld from './HelloWorld';
render(<HelloWorld />);
运行应用程序
在 package.json 中添加启动脚本:

{
"scripts": {
"start": "node index.js"
}
}
然后通过以下命令运行:
npm start
使用高级功能
Ink 提供了多种内置组件和钩子,例如 Box、Text、useInput 等。以下是一个使用 useInput 处理用户输入的示例:
import React from 'react';
import { Text, useInput } from 'ink';
const App = () => {
useInput((input) => {
if (input === 'q') {
process.exit();
}
});
return <Text>Press 'q' to exit</Text>;
};
export default App;
样式和布局
使用 Box 和样式属性控制布局和外观:

import React from 'react';
import { Box, Text } from 'ink';
const StyledBox = () => (
<Box borderStyle="round" borderColor="cyan" padding={2}>
<Text color="yellow">Styled Box</Text>
</Box>
);
export default StyledBox;
处理异步操作
利用 useState 和 useEffect 处理异步数据加载:
import React, { useState, useEffect } from 'react';
import { Text } from 'ink';
const AsyncComponent = () => {
const [data, setData] = useState(null);
useEffect(() => {
fetchData().then(setData);
}, []);
return <Text>{data ? `Data: ${data}` : 'Loading...'}</Text>;
};
export default AsyncComponent;
调试和错误处理
在开发过程中,可以通过 console.log 或 console.error 输出调试信息。对于错误边界,使用 React 的 ErrorBoundary 模式:
import React from 'react';
import { Text } from 'ink';
class ErrorBoundary extends React.Component {
state = { hasError: false };
static getDerivedStateFromError() {
return { hasError: true };
}
render() {
if (this.state.hasError) {
return <Text color="red">Something went wrong.</Text>;
}
return this.props.children;
}
}
export default ErrorBoundary;
构建和发布
使用 pkg 或 nexe 将应用程序打包为可执行文件:
npm install -g pkg
pkg index.js --targets node16-macos-x64,node16-linux-x64,node16-win-x64
以上步骤涵盖了从基础到高级的 Ink 和 React 使用方法,适用于构建终端应用程序。




