Ionic tuning of the electrical and optical properties of two-dimensional materials