如何使用ink react
安装 Ink React
确保系统已安装 Node.js(建议版本 12 或更高)。通过 npm 或 yarn 安装 ink 和 react 依赖包:
npm install ink react
或
yarn add ink react
创建基础组件
Ink 允许使用 React 语法编写命令行界面。创建一个简单的组件文件(如 cli.js):
import React from 'react';
import { render, Text } from 'ink';
const App = () => <Text color="green">Hello, Ink!</Text>;
render(<App />);
运行组件
通过 Node.js 执行组件文件:
node cli.js
终端将显示绿色文本 "Hello, Ink!"。
添加交互功能
Ink 支持用户输入和动态更新。使用 useState 和 TextInput 组件实现输入交互:

import React, { useState } from 'react';
import { render, Text, TextInput } from 'ink';
const App = () => {
const [input, setInput] = useState('');
return (
<>
<Text>Enter your name: </Text>
<TextInput value={input} onChange={setInput} />
<Text>You typed: {input}</Text>
</>
);
};
render(<App />);
处理命令行参数
通过 process.argv 或第三方库(如 yargs)获取命令行参数:
import React from 'react';
import { render, Text } from 'ink';
const App = () => <Text>Args: {process.argv.join(' ')}</Text>;
render(<App />);
使用布局组件
Ink 提供 Box 和 Newline 等布局组件控制输出格式:
import { render, Box, Text, Newline } from 'ink';
const App = () => (
<Box flexDirection="column">
<Text>First line</Text>
<Newline />
<Text color="yellow">Second line</Text>
</Box>
);
render(<App />);
生命周期管理
通过 useEffect 处理组件生命周期,如定时更新:

import React, { useState, useEffect } from 'react';
import { render, Text } from 'ink';
const App = () => {
const [count, setCount] = useState(0);
useEffect(() => {
const timer = setInterval(() => setCount(c => c + 1), 1000);
return () => clearInterval(timer);
}, []);
return <Text>Count: {count}</Text>;
};
render(<App />);
错误边界
使用 ErrorBoundary 捕获子组件错误:
import { render, ErrorBoundary, Text } from 'ink';
const BuggyComponent = () => { throw new Error('Crash!'); };
const App = () => (
<ErrorBoundary fallback={({ error }) => <Text color="red">{error.message}</Text>}>
<BuggyComponent />
</ErrorBoundary>
);
render(<App />);
测试组件
Ink 支持通过 ink-testing-library 进行单元测试:
npm install --save-dev ink-testing-library
测试示例:
import { render } from 'ink-testing-library';
import { App } from './cli';
test('displays greeting', () => {
const { lastFrame } = render(<App />);
expect(lastFrame()).toContain('Hello, Ink!');
});
打包发布
使用 pkg 或 nexe 将应用打包为可执行文件:
npm install -g pkg
pkg cli.js --targets node14-linux-x64
生成的可执行文件可直接运行无需 Node.js 环境。






