如何使用ink react
安装 Ink 和 React
确保 Node.js 版本在 12 或更高版本。通过 npm 或 yarn 安装 Ink 和 React:
npm install ink react
创建基础组件
创建一个简单的 React 组件,使用 Ink 提供的 <Text> 或其他内置组件渲染文本:
import React from 'react';
import { Text } from 'ink';
const App = () => <Text color="green">Hello, Ink!</Text>;
export default App;
运行 Ink 应用
使用 ink-cli 或直接通过 Node 运行编译后的文件。推荐通过 ink-cli 快速启动:
npx ink-cli your-component.js
处理用户输入
通过 useInput Hook 监听键盘事件,实现交互功能:

import React from 'react';
import { useInput, Text } from 'ink';
const App = () => {
useInput((input) => {
if (input === 'q') process.exit();
});
return <Text>Press 'q' to exit</Text>;
};
使用布局组件
Ink 提供 <Box> 和 <Static> 等布局组件,用于控制终端显示格式:
import { Box, Text } from 'ink';
const LayoutExample = () => (
<Box flexDirection="column">
<Text>Top</Text>
<Text>Bottom</Text>
</Box>
);
添加样式
通过 color、backgroundColor 等属性设置文本样式,或使用 chalk 库扩展颜色:

<Text color="#FF8800" backgroundColor="black">
Styled text
</Text>
生命周期管理
使用 React 的 useEffect 清理资源,或通过 useApp 获取退出控制权:
import { useApp } from 'ink';
const App = () => {
const { exit } = useApp();
setTimeout(() => exit(), 3000);
return <Text>Exiting in 3 seconds...</Text>;
};
调试与日志
在开发时启用调试模式,输出额外信息:
DEBUG=ink* npx ink-cli app.js
打包发布
使用 esbuild 或 tsup 打包项目为单一可执行文件,便于分发:
npx esbuild app.js --bundle --platform=node --outfile=dist/app.js





