First law of black hole mechanics in Einstein-Maxwell and Einstein-Yang-Mills theories